Why can't I pass the directory as an argument to the for loop in bash?

I have a simple bash script, simple.sh, as shown below:

#/usr/local/bin/bash for i in $1 do echo The current file is $i done 

When I run it with the following argument:

 ./simple.sh /home/test/* 

it will print and output only the first file located in the directory.

However, if I changed my simple.sh file to:

 #/usr/local/bin/bash DIR=/home/test/* for i in $DIR do echo The current file is $i done 

it will print files in the directory correctly. Can someone explain why the argument passed does not show the same result?

+7
source share
4 answers

If you take "$ 1", this is the first file / directory that is possible! You should do it like this:

 for i in " $@ " do echo The current file is ${i} done 

If you execute it with:

 ./simple.sh * 

They list all real dictionary files

"$ 1" is the alphabet of the first file / directory of your current directory, and in the for loop the value of "i" will be, for example, a1.sh, and then they will exit the for! If you do:

 DIR=/home/<s.th.>/* 

You save the value of all files / directories in DIR!

+8
source

It is just as portable as it has no useless forks for ls and works with a minimum number of processor cycles:

 #!/bin/sh cd $1 for i in *; do echo The current file is "$i" done 

Run as ./simple.sh /home/test

+1
source

Your script does not get "/ home / test / *" as an argument; the shell extends patter to a list of files that match, and your shell receives several arguments, one per file. Quoting the argument will work:

 ./simple.sh "/home/test/*" 

Your change to using DIR=/home/test/* did what you expected, because file name generation is not performed in the RHS variable assignment. When you left $DIR without quotes in a for loop, the template was expanded to a list of matching files.

+1
source

How about a manully file list instead of using *:

  #/usr/local/bin/bash for i in $(ls $1) do echo The current file is $i done 

and enter

  ./simple.sh /home/test/ 
-2
source

All Articles