Newbie to bash
anybody know the problem it seems quite easy to solve but I just can't figure it out myself!
basically the command I am making does something to the arguments that the user enters, these arguments are filenames [THIS IS FOR AN ASSIGNMENT SO I CANT DISCUSS CONTENTS] lets just say it lists the files for example sake
there is no limit to the number of files that the user can type THE CODE (MAIN BIT THAT HAS PROBLEM)
if [ -e "$*" ]
then
ls "$*"
echo "your files are listed"
else
echo "file does not exist"
exit 0
fi
basically the if statement doesnt work for some reason
i want it so that the user can type in as many arguments as they want
and the if statement will check if all the arguments (files) exist
so far when i just type in 1 argument it checks if it exists
but when i type in more than 1 then it pops up with error "too many arguments" and the error message that it doesnt exist
HELP WOULD BE APPRECIATED :)
and if you feel that you will be helping me cheating dont worry the main code is okay it works but its just this validation bit!
test -e
expects a single file to be the next argument. "$*"
, by contrast, smooshes all your arguments together into just one name -- so if you have files named first file.txt
and second file.txt
, [ -e "$*" ]
will look at whether a single file named something like first file.txt second file.txt
(with the spaces and both .txt
extensions in its name) is present.
for file in "$@"; do ## this could also be just "for file; do"
if ! [ -e "$file" ]; then ## note that we're checking one at a time
echo "File $file does not exist" >&2
exit 1
fi
ls "$file" ## hopefully this is just for debugging
done
echo "Your files all exist" >&2
exit 0 ## typically unnecessary -- default exit status is that of the last command
## ...and echo is unlikely to fail.
Note that ls
should not be used programatically, and even if you did want to print names only of files that actually exist for human consumption (as opposed to scripted/programmatic use), it would be more efficient to call ls
once with all the names that exist, vs once-per-file; fixing that, however, isn't clearly within the scope of the question as-asked.