Issue
I wish to dynamically get the first file inside a folder. What I have tried so far:
get_first_file () {
local folder_name=$1
filenames=`ls $folder_name/*`
first_file=(echo ${filenames} | awk '{print $1}')
get_first_file my_folder
This produces the following error:
my_shell_script.sh: line 4: syntax error near unexpected token `|'
my_shell_script.sh: line 4: ` first_file=(echo ${filenames} | awk '{print $1}')'
Please help me understand what this error means, and how it can be resolved.
Solution
There are several issue with your code. I'll just address the syntax errors:
get_first_file () {
local folder_name=$1
filenames=`ls $folder_name/*`
first_file=$(echo ${filenames} | awk '{print $1}')
}
get_first_file my_folder
There's really no need for the intermediate variables, but perhaps you are using filenames
at the global scope, so there's nothing wrong with using them. Backticks have been effectively obsolete for decades and should never be used, and parsing the output of ls
like this is generally not a good idea.
You really ought not do this, though. In particular, allowing word splitting on the echo to munge all the whitespace and generate a single line of output to be filtered by awk
is weird. You can get away with this if your filenames are well behaved, but it's not good practice. Perhaps it would be better to write something like:
get_first_file () {
first_file=$(for i in *; do echo "$i"; exit; done;)
}
or
get_first_file () {
first_file=$(find "$1" -not -name '.*' -maxdepth 1 -print0 |
perl -0ne 'print if $. == 1')
}
but it's not clear what you're doing with filenames
Answered By - William Pursell