I want to stored all command args
in an array
but it only works when all args have no any (*
).
Here is a test without using array:
mkdir -p /tmp/hello
echo "hello" > /tmp/hello/hello.txt
echo "world" > /tmp/hello/world.txt
mkdir -p /tmp/world
# This cp command is success
cp /tmp/hello/* /tmp/world
Now convert the cp command into my_array:
mkdir -p /tmp/hello
echo "hello" > /tmp/hello/hello.txt
echo "world" > /tmp/hello/world.txt
mkdir -p /tmp/world
declare -a my_array=()
my_array[0]="cp"
my_array[1]="/tmp/hello/*"
my_array[2]="/tmp/world"
# Run the command and it will fail
"${my_array[@]}"
Here is the error:
cp: cannot stat '/tmp/hello/*': No such file or directory
Is it possible for using (*
) in the my_array
?
What's the correct syntax for implementing the 'cp /tmp/hello/* /tmp/world
' with my_array
?
Update:
There is a problem
from @choroba's answoer
, The $count
and $sedond_item
will be wrong:
mkdir -p /tmp/hello
echo "hello" > /tmp/hello/hello.txt
echo "world" > /tmp/hello/world.txt
mkdir -p /tmp/world
my_array=(cp)
my_array+=(/tmp/hello/*)
my_array+=(/tmp/world)
count=${#my_array[@]}
printf "%s\n" "count is: $count"
sedond_item="${my_array[1]}"
printf "%s\n" "second item is: $sedond_item"
Here is the output of @choroba's answoer:
count is: 4
second item is: /tmp/hello/hello.txt
But the $count
and $sedond_item
are correct in my original array:
mkdir -p /tmp/hello
echo "hello" > /tmp/hello/hello.txt
echo "world" > /tmp/hello/world.txt
mkdir -p /tmp/world
declare -a my_array=()
my_array[0]="cp"
my_array[1]="/tmp/hello/*"
my_array[2]="/tmp/world"
count=${#my_array[@]}
printf "%s\n" "count is: $count"
sedond_item="${my_array[1]}"
printf "%s\n" "second item is: $sedond_item"
Here is the output of original array:
count is: 3
second item is: /tmp/hello/*
/tmp/hello/*
to be expanded when the array is created, or when the command is run?/tmp/hello/
*" to be expanded only when I call the "${my_array[@]}
" in my bash script.eval "${my_array[@]}"
will join the elements ofmy_array
and run it as a command, fully expanding*
.