Reputation: 14318
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.
Upvotes: 0
Views: 900
Reputation: 780909
You need to use eval
to get the quotes processed.
eval "scriptArgs=($args)"
Upvotes: 2