Command works interactively but not in bash script

The below command works in the terminal interactively but not as part of a bash script . I though maybe I needed to escape the "$dir" so it isn't interpreted literally, but that's not it. Thank you :).

interactively in terminal

dir=/path/to
new=$(ls "$dir"/*.csv -tr | tail -n 1) && echo "the current csv is from: " && date -r "$new" "+%m/%d/%Y"

the current csv is from: 
10/31/2019

as part of #!/bin/bash

the current csv is from:

Hi,

I'm not getting the same error, although I've tested running the shell from the same directory as the test data and a different directory;

Is there more to the script - see below for the test.

fbakirpomd5 (root) /root-> pwd
/root
fbakirpomd5 (root) /root-> ls *.csv
file_o1.csv
fbakirpomd5 (root) /root-> cat test.sh
#!/bin/bash
dir=/root
new=$(ls "$dir"/*.csv -tr | tail -n 1) && echo "the current csv is from: " && date -r "$new" "+%m/%d/%Y"
fbakirpomd5 (root) /root-> ./test.sh
the current csv is from:
05/14/2019
fbakirpomd5 (root) /root-> /usr/local/bin/test.sh
the current csv is from:
05/14/2019
fbakirpomd5 (root) /root->

Regards

Gull04

1 Like

Please post operating system details.

Can you show output from :

which bash
head -1 <your script> | od -cb

Regards
Peasant.

1 Like

Difficult to believe. Any error messages? is dir exported / defined (within the script)?

Try also

stat -c"the current csv is from: %y" *.csv | sort -r -k6,6 | head -1
1 Like

I found the error in the script... thank you :).

1 Like

After 1300ish posts one should know to post error you found.
This will benefit others and be in search results.

So, please, post the solution.

Regards
Peasant.

2 Likes

Maybe this will help others:

In $dir the were multiple csv files that were the same name, so I needed to add a condition to remove all but the last modified that matched the file I was looking for.

awk -F, '/Date/ {print $2}' "$new" (extracted the current) that I compared to the date -r "$new" "+%m/%d/%Y" (these had to match) then the $new was unique and the script worked. Thank you :).