I'm practicing shell scripts and am trying to make a simple script that takes a directory as an argument, loops through each file within and prints out its name and size.
#!/bin/bash
# A practice shell script to try and display a list of file names
# and their sizes using the output of ls -l and cut.
declare -i index
export index=0
export name=""
export size=0
for file in $1 ; do
index+=1
name=basename $file
size=ls -l $file | cut -d " " -f 5
echo "$index: $name, size: $size bytes"
done
When I give ./*
as the argument, it does it for one file and that's it. However, if I edit the code above and just put ./*
in place of $1
, it works and loops through all files in the current directory.
Why won’t it do the same, when $1
is supposed to equal ./*
?
"$@"
(with double-quotes) instead of$*
because of possible word-splitting (see e.g. alternative 2 I mentioned in my answer). – AdminBee Dec 03 '21 at 09:27