Reading multiple files/folders with shellscript - linux

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

Related

While loop to test if a file exists in bash script

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

why if expression is always true in bash script

I'm very new in shell script and I wrote this code to copy an input file from directory new1 to directory new2 if the file doesn't exist in second directory.
the problem is that the first if expression is always true and the code always print "file copied successfully" even if the file exists in second directory.
here is my code:
while true; do
echo "enter a file name from directory new1 to copy it to directory new2 "
echo "or enter ctrl+c to exit: "
read input
i=0
cd ~/new2
if [ -f ~/new1/$input ]; then
i=1
fi
if [ $i -eq 0 ];then
cp ~/new1/$input ~/new2/
echo "####" $input "copied successfully ####"
else
echo "#### this file exist ####"
fi
done
I will be appreciated if any one tell me how to fix this problem
You are comparing the wrong file. In addition, you probably want to refactor your logic. There is no need to keep a separate variable to remember what you just did.
while true; do
echo "enter a file name from directory new1 to copy it to directory new2 "
echo "or enter ctrl+c to exit: "
read input
#i=0 # no use
#cd ~/new2 # definitely no use
if [ -f ~/new2/"$input" ]; then # fix s/new1/new2/
# diagnostics to stderr; prefix messages with script's name
echo "$0: file ~/new2/$input already exists" >&2
else
cp ~/new1/"$input" ~/new2/
echo "$0: ~/new1/$input copied to ~/new2 successfully" >&2
fi
done
Take care to make your diagnostic messages specific enough to be useful. Too many beginner scripts tell you "file not found" 23 times but you don't know which of the 50 files you tried to access were not found. Similarly, including the name of the script or tool which produces a diagnostic in the diagnostic message helps identify the culprit and facilitate debugging as you start to build scripts which call scripts which call scripts ...
As you learn to use the command line, you will find that scripts which require interactive input are a dog to use because they don't offer command history, tab completion of file names, and other niceties which are trivially available to any tool which accepts a command-line file argument.
cp -u already does what this script attempts to implement, so the script isn't particularly useful per se.
Note also that ~ is a Bash-only feature which does not work with sh. Your script otherwise seems to be compatible with POSIX sh and could actually benefit from some Bash extensions such as [[ if you are going to use Bash features anyway.

Bash scripting and comparing 2 directories - Beginner

My problem is that i have to check what files are included in the $directory, then i have to make a new file with name specified by me and compare if the name doesn't already exist in this directory (compare 2 directories).
Below is my code:
directory=$(pwd -L "/$nameProject")
read -p "Enter repo name: " nameRepo
# Check if repo name exists in $directory
if [$(find "$directory/$nameProject" -path "$directory/$nameProject/*")==$("$directory/$nameProject/$nameRepo")]; then
instruction..
fi
Thank you for any help!
Did you try
if [[ ! -d "$directory/$nameProject/$nameRepo" && ! -f "$directory/$nameProject/$nameRepo"]] ; then
mkdir "$directory/$nameProject/$nameRepo"
fi
You can split the above if loop into two and print appropriate error by removing !
Spaces are important to the shell. So is quoting. You need spaces around [ and == and ] (though ]; is ok). (Also technically the comparison operator is = and not ==.).
Also find can return more than one result which will cause problems for your test.
If you want to test whether a directory (or file) with a given name exists then you don't need (or want) to use find. You can just use the -d and -f (and -e) tests of the [ test binary/built-in directly(spec, bashref).
if [ -d path/to/directory ]; then
echo "Was a directory"
else
echo "Was not a directory"
fi

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.

Remove in linux

hey so I have some code for the question bellow but I am stuck its not working and I don't really know what I am doing.
This script should remove the contents of the dustbin directory.
If the -a option is used the script should remove ALL files from the dustbin.
Otherwise, the script should display the filenames in the dustbin one by one and ask the user for confirmation that they should be deleted
#!/bin/sh
echo " The files in the dustbin are : "
ls ~/TAM/dustbin
read -p " Please enter -a to delete all files else you will be prompted to delete one by one : " filename
read ans
if ["filename" == "-a"]
cat ~/TAM/dustbin
rm -rf*
else
ls > ~/TAM/dustbin
for line in `cat ~/TAM/dustbin`
do
echo "Do you want to delete this file" $line
echo "Y/N"
read ans
case "ans" in
Y) rm $line ;;
N) "" ;;
esac
EDITED VERSION
if test ! -f ~/TAM/dustbin/*
then
echo "this directory is empty"
else
for resfile in ~/TAM/dustbin/*
do
if test -f $resfile ; then
echo "Do you want to delete $resfile"
echo "Y/N"
read ans
if test $ans = Y ; then
rm $resfile
echo "File $resfile was deleted"
fi
fi
done
fi
this works however Now I get one of 2 errors either
line 4 requires a binary operator or line 4: to many arguments
I see one obvious mistake:
rm -rf*
when it should be
rm -rf *
to be asked about every file deletion - add -i key
rm -rfi *
Many problems here:
A space missing before the * in rm. The space is needed so the shell can recognize the wildcard and expand it.
Do you really want to remove all the files in the current directory? If not, specify the path rm -rf /path/to/files/* or cd into the directory, preferably with cd /path/to/files || exit 1.
I do not understand the logic of the script. You show a dustbin, but if the user gives -a, you overwrite it with all the non-hidden files (ls > dustbin). Is that what you want?
First of all, case "ans" of just matches a string "ans" to other strings, which is obviously false, you need case $ans of to get the value of variable ans. if ["filename" == "-a"] is also comparison between two strings, which is always false. The first parameter of a script can be accessed as $1 (the second as $2 and so on).
Please read man 1 sh to get the basics of shell programming (all of the above notes can be found there).

Resources