In a simple cycle like the following
for f in $(ls -1) ; do something done
I would like to store each line of the output of
ls -1 in the variable
Is there a way to do this without setting
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
As we said in the comments, don't parse
ls it is prone to errors and completely unnecessary anyway. All you need is
for f in *; do something done
That will iterate through the files and directories1 in your current directory and save each of them (spaces and all) as
$f. For example:
$ ls -A1 file1 file 2 $ for f in *; do echo "File is '$f'"; done File is 'file1' File is 'file 2'
1 In bash, this will ignore files/directory names starting with
. (hidden files) unless you have set
shopt -s dotglob.
Use while loop instead:
$ touch "one file" $ touch "second file edsfs" $ ls one file second file edsfs $ ls -1 one file second file edsfs $ for f in $(ls -1); do echo "\"$f\""; done "one" "file" "second" "file" "edsfs" $ while read f; do echo "\"$f\""; done < <(ls -1) "one file" "second file edsfs"