I wrote a simple bash script (I'm pretty new to it, you know!) to accept a directory as its argument and print its listing, testing for files and directories. Here's how I approached it:
#!/bin/bash
# Lists all files and directories (non-recursively) in a specified directory
if [ $# -gt 1 ]; then
echo "Error. Please specify only one directory. ($#)"
exit
fi
if [ -z $1 ]; then
echo "No directory specified. Exiting."
exit
fi
echo "Listing for $1:"
$dirs=`ls $1`
echo "Dirs: $dirs" # Just to confirm if all is well
# Loop through and print
for i in $dirs;
do
if [ -f $i ]; then
echo "File: $i"
elif [ -d $i ]; then
echo "Directory: $i"
fi
done
The problem is in my for loop. When I run this script and feed it my home directory, I get this error:
./list_files_and_dirs.sh: line 16: =Calibre: command not found
I know I'm making a mistake in command substitution involving variables, but I just don't know what. Someone please help!
================= Update =================
Here's the new (final section) code as per inputs from answers:
dirs=`ls "$1"`
#echo "Dirs: $dirs" # Just to confirm if all is well
IFS=$'\n'
# Loop through and print
for i in $dirs;
do
if [ -f "$i" ]; then
echo "File: $i"
elif [ -d "$i" ]; then
echo "Directory: $i"
fi
done