0

I'm using a VS Code task to run a script that runs my jest tests on the currently opened file. It prompts me to type in a test pattern and, if something is entered, passes the value in as an environment variable. I want to split that variable an array to be modified passed in as arguments to my jest call. Because test names almost always include spaces (or any other character), I want to be able to be able to pass multiple patterns with quotes around them.

Input

"test 1" "test 2" "test 3"

Generated environment variables

args='"test 1" "test 2" "test 3"'
testFile="path/to/currently opened/file"

Desired command to run in script:

npm run test -- "path/to/currently opened/file" -t "test 1" -t "test 2" -t "test 3"

I've figured out how to do everything except evaluate $args as an array. Here's what I have to test various attempts at parsing this.

#!/bin/bash

echo "$args"
echo

scriptArgs=( $args )
echo ${#scriptArgs}
echo ${#scriptArgs[@]}
echo

scriptArgs=( "${args[@]}" )
echo ${#scriptArgs}
echo ${#scriptArgs[@]}
echo

scriptArgs=( "$args" )
echo ${#scriptArgs}
echo ${#scriptArgs[@]}
echo

scriptArgs=( $(echo $args) )
echo ${#scriptArgs}
echo ${#scriptArgs[@]}
echo

scriptArgs=( "$(echo $args)" )
echo ${#scriptArgs}
echo ${#scriptArgs[@]}
echo

# prints:
#
#  "test 1" "test 2" "test 3"
#  
#  5
#  6
#  
#  26
#  1
#  
#  26
#  1
#  
#  5
#  6
#  
#  26
#  1

The desired value is 3.

3
  • 1
    If you could easily convert a string like args into an array, there wouldn't be a need for arrays in the first place. Commented Jul 12, 2020 at 19:52
  • @dx_over_dt : Why don't you simply define args as array? args=('test 1' 'test 2' 'test 3')? Commented Jul 13, 2020 at 11:47
  • @user1934428 I don't have that option. VS Code ensures that the environment is a single escaped value. Commented Jul 13, 2020 at 15:04

1 Answer 1

2

You need to use eval to get the quotes processed.

eval "scriptArgs=($args)"
Sign up to request clarification or add additional context in comments.

1 Comment

Well that was easy. It's good to learn the eval keyword exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.