I have a simple bash script, simple.sh, as follows:
#/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 would only print and list out the first file located in the directory.
However, if I change my simple.sh to:
#/usr/local/bin/bash
DIR=/home/test/*
for i in $DIR
do
echo The current file is $i
done
it would correctly print out the files within the directory. Can someone help explain why the argument being passed is not showing the same result?
If you take "$1", it is the first file/directory, which is possible! You should do it in this way:
for i in "$@"
do
echo The current file is ${i}
done
If you execute it with:
./simple.sh *
They list you all files of the actual dictionary
"$1" is alphabetical the first file/directory of your current directory, and in the for loop, the value of "i" would be e.g. a1.sh and then they would go out of the for loop! If you do:
DIR=/home/<s.th.>/*
you save the value of all files/directories in DIR!
This is as portable as it gets, has no useless forks to ls and runs with a minimum of CPU cycles wasted:
#!/bin/sh
cd $1
for i in *; do
echo The current file is "$i"
done
Run as ./simple.sh /home/test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With