I'm writing my first bash script as part of homework and given covid 19 we haven't been able to go over some of this stuff in class (and I'm not doing well googling).
I am writing a script that takes user input and searches the cd to find a file with the name of $userInput. If found the script will determine if the file is a "normal file" (.txt for example) or if the file is a directory. How can I gather this information?
Here is my code currently:
#! /bin/bash
$userInput
echo "Enter a file name. Empty to exit."
while [ 1 ]
do
echo "Please input a file name:"
read userInput
if [ "$userInput" == "" ]; then
exit
else
echo $userInput
fi
done
I have the looping and getting user input down, what am I missing here?
if cd $userInput*; then
cd ..
echo "It is a directory."
else
# the cd will do the rest of informing for you
fi
I also strongly suggest to turn this into a file and get user input in command line, like this:
bash ./yourcode.sh filename
Inside your code:
if cd $1*; then
cd ..
echo "It is a directory."
else
# the cd will do the rest of informing for you
fi
EDITED: EXTRA
Continue here if you really wanna understand what happened. In bash, every command/function by default returns a value that informs the kernel whether it terminated successfully or something went wrong, for sake of simplicity, we will just assume it returns true
if successful and false
if not, here I used this piece of info with the function cd
which changes the current directory to the one specified, if the change happened successfully, it will return true
which then I will capture in my if
statement to execute the code, which consists of returning to the original directory ( cd ..
) and saying to the user it was a directory. Otherwise, cd
will return false and will tell you itself what happened, was it a file or was it nonexistent, and the *
(a wildcard) exists to find whatever extension it might have or even doesn't have. I hope this helps, cheers!
There are several ways to classify an entry. For instance,
[[ -f $filename ]]
tests for regular files,
[[ -d $filename ]]
tests for directories, and there are other tests too where you can test for symlinks, or whether you have read/write/execute permissions. You find the list of available file test operators here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.