While loop to test if a file exists in bash script - linux

I am trying to create a loop to prompt the user to create a file. If the file already exists, it will keep prompting the user until the user enters a file that does not exist. But can't seem to get it to work, anyone can help, please?
file3=/root/simulate/$filename
while true ; do
if [ ! -f "$file3" ]; then
read -p "Please enter a file name to create in simulate folder:" filename
touch /root/simulate/$filename
elif [ -f "$file3" ]; then
read -p "Please enter a different file name as $filename already exist:" filename
touch /root/simulate/$filename
break
else
touch /root/simulate/$filename
fi
done

filename variable is empty.
There are two way to fill in filename variable
filename variable can pass on shell script by export command.
ex) $export filename=newFile
if you execute shell script, shell is forking and execute new shell. new shell taken your mother shell's Environment variables
Push filename variable into shell script.
note: I picked second way and I changed path of $file3.
I fixed codes in block of elif to ask again if something goes wrong.
this is a code.
#!/bin/bash
filename=newFile
file3="./$filename"
while true ; do
if [ ! -f "$file3" ]; then
read -p "Please enter a file name to create in simulate folder:" filename
touch ./$filename
break
elif [ -f "$file3" ]; then
while true ; do
read -p "Please enter a different file name as $filename already exist:" filename
if [ ! -f "$filename" ]; then
touch ./$filename
break 2
fi
done
else
touch ./$filename
fi
done

Related

Why can't change the input data if the variable declaration is inside of a for loop in bash

So im trying to make an infinity loop, that creates libraries.
but the file variable take input only once.
code:
for (( ; ; ))
do
file=${1?Error: no input}
mkdir "$file"
sleep 1
done
There's nothing in that loop that asks for input. $1 is provided once by the user as they run the script (before the loop even starts). The standard way to request input in a shell script is with the read command. Something like this:
while read -p "Enter a directory to create: " file; do
mkdir "$file"
done
This loop will terminate when it receives an end-of-file, which means the user must press Control-D to exit it. If you want to exit if the user just presses return without entering anything, you could do this:
while read -p "Enter a directory to create: " file; do
if [ -z "$file" ]; then
echo "Error: no input" >&2
break # This exits the while loop
fi
mkdir "$file"
done

Using ls command result in a loop

I want to use the result of ls command in a loop to check if for example the first line is a directory, second etc.
For example I have this folder that contains one directory the script should display:
18_05_2018 is directory
enter image description here
Create a file named is_file_or_directory.sh containing:
cd "$1" || echo "Please specify a path" && exit
for i in *; do
if [[ -d $i ]]; then
echo "$i is a directory"
elif [[ -f $i ]]; then
echo "$i is a file"
else
echo "$i is not valid"
exit 1
fi
done
Make that file executable with:
sudo chmod +x is_file_or_directory.sh
Run the script specifying as a parameter the path that you want to analyze:
./is_file_or_directory.sh /root/scripts/
Output:
jeeves ~/scripts/stack # ./is_file_or_dir.sh /root/scripts/
databe.py is a file
is_file_or_dir.sh is a file
mysql_flask.py is a file
test is a directory
Here's a more detailed explanation of what is happening under the hood. The variable $1 is, in Bash, the first parameter sent to the script. In our case it is the path where the script will perform its actions. Then we use the variable $i in the loop.
$i content will be every file / folder name in the path $1. With -d and -f we check if $i is a file or a folder.

Reading multiple files/folders with shellscript

I am using the read command to capture the files/folder names and further checking if they exist but below script only works with a single file/folder and does not work to capture multiple files/folders. Please help!
Thank you!
echo -n "Please enter a name of file/folder you wish to backup: "
read FILE
while [ ! -e "$FILE" ] ;do
read -p "The file ["$FILE"] does not exist."
echo -n "Please enter a name of file/folder you wish to backup: "
read FILE
done
I recommend taking an approach similar to this:
You can use CTRL + C to force an exit.
Please note that this should really be an if statement like to
ensure proper flow of logic as && || does not equate to if
then else logic
if [ "foo" = "foo" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
https://github.com/koalaman/shellcheck/wiki/SC2015

How to create a shell script that can scan a file for a specific word?

one of the questions that I have been given to do for my Computer Science GCSE was:
Write a shell script that takes a string input from a user, asks for a file name and reports whether that string is present in the file.
However way I try to do it, I cannot create a shell script.
I don't need you to tell me the whole number, however, I have no idea where to start. I input the variable and the file name, however, I have no idea how to search for the chosen word in the chosen file. Any ideas?
Using grep can get this working, for example
viewEntry()
{
echo "Entering view entry"
echo -n "Enter Name: "
read input
if grep -q "$input" datafile
then
echo ""
echo -n "Information -> "
grep -w "$input" datafile
echo ""
else
echo "/!\Name Not Found/!\\"
fi
echo "Exiting view entry"
echo ""
}
dataFile is the file you would be reading from. Then making use of -q and -w arguments of grep, you should be able to navigate your chosen file.
This site does a great job explaining grep and your exact problem: http://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/
The following shell-script is a very quick approach to do what you suggested:
#!/bin/sh # Tell your shell with what program this script should be exectued
echo "Please enter the filename: "
read filename # read user input into variable filename
count=`grep -c $1 $filename` # store result of grep into variable count
if [ $count -gt 0 ] # check if count is greater than 0
then
echo "String is present:" $1
else
echo "String not found:" $1
fi
You should look at some tutorials to get the basics of shell-scripting. Your task isn't very complex, so after some reading you should be able understand what the script does and modify it according your needs.

Linux file deletion error

Every time I run this code I get the error File or directory doesn't exist. Why?
read -p "Enter the filename/path of the file you wish to delete : " filename
echo "Do you want to delete this file"
echo "Y/N"
read ans
case "$ans" in
Y) "`readlink -f $filename`" >>~/TAM/store & mv $filename ~/TAM/dustbin
echo "File moved" ;;
N) "File Not deleted" ;;
esac
When I enter the file name/directory exactly and triple check its right I still get this error, but the readlink part works.
Paraphrasing/summarizing/extending my answer for a similar question:
I doubt you really meant to use & instead of && in your script.
"File Not deleted" is not a valid command on any Linux system that I have used. Perhaps you are missing an echo there?
You have to fix your variable quotation. If the filename variable contains whitespace, then $filename is expanded by the shell into more than one arguments. You need to enclose it into double quotes:
mv "$filename" ~/TAM/dustbin
I do not see your script creating the ~/TAM/ directory anywhere...
You are missing an echo and one &&.
Use echo "`command`" to pipe the result string of commands. Alternatively, you may directly use the command without backticks and quotes, (not storing the result in a string), in which case you do not need an echo because the command will pipe its result to the next command.
The single & will run the preceding command in the background (async.). To check for return values and conditionally execute you need && and ||.
Here is a complete solution/example (incl. some more logging):
# modified example not messing the $HOME dir.
# should be save to run in a separate dir
touch testfile #create file for testing
read -p "Enter the filename/path of the file you wish to delete : " filename
echo "Do you want to delete this file: $filename"
echo "Y/N"
read ans
touch movedfiles #create a file to store the moved files
[ -d _trash ] || mkdir _trash #create a dustbin if not already there
case "$ans" in
Y) readlink -f "$filename" >> movedfiles && echo "File name stored" &&
mv "$filename" _trash && echo "File moved" ;;
N) echo "File Not deleted" ;;
esac
cat movedfiles #display all moved files

Resources