Sample Header Ad - 728x90

bash array acting weird

1 vote
1 answer
279 views
I have two folders under /tmp. **From terminal:**
ls -d /tmp/firefox-*

/tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile
or
compgen -G /tmp/firefox-*

/tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile
And i can store the output in an array as well:
arr=( $(ls -d /tmp/firefox-*) )
echo $arr
tmp/firefox-sy2vakcj.default-esr-charlie-cache  /tmp/firefox-sy2vakcj.default-esr-charlie-profile
 
echo $arr 
tmp/firefox-sy2vakcj.default-esr-charlie-cache

echo $arr
/tmp/firefox-sy2vakcj.default-esr-charlie-profile
so far so good. But if i attempt the same thing from a script:
...
    ... 
    arr=( "$(ls -d /tmp/firefox-*)" ) ||( echo "directory doesn't exist" && exit 1)
    #arr=( "$(compgen -G /tmp/firefox-*)" ) ||( echo "directory doesn't exist" && exit 1)
    echo "this is a test for arr: $arr"
    echo "this is a test for arr: $arr"
    ...
I get the output: **From script:** for
-d
this is the output:
+ arr=("$(ls -d /tmp/firefox-*)")
++ ls -d '/tmp/firefox-*'
ls: cannot access '/tmp/firefox-*': No such file or directory
+ echo 'directory doesn'\''t exist'
directory doesn't exist
and for
-G
, this is the output:
this is a test for arr: /tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile
this is a test for arr: /tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile
**My questions:** **1.** Why is the glob not expanding in the subshell for the command
-d
? **2.** With
-G
, how are the values being stored in the array? the output seems like each entry in the array is storing both the directory entry with the second one with its own index array? **3.** Is the output from terminal for both commands different from the script, or am i missing something?
Asked by Just Khaithang (442 rep)
Oct 19, 2021, 09:23 AM
Last activity: Oct 19, 2021, 02:41 PM