Else if loop command depending on result string - bash

I am trying to have a script take an argument and run a command against it and retry the command if a result matches a certain string. Otherwise other results will echo the result.
We have a script at work where we run "rm <filename>" but it takes 5 seconds to return whether successful or not and I want to make a script to keep running it until it sees a "destroyed file" string in the result.
This is what I have so far..
#!/bin/bash
function rm () {
if [[ $(rm $1 | grep -m 1 'destroyed file') ]] ; then
echo "Destroyed File"
elif [[ $(rm $1 | grep -m 1 'remove failed') ]] ; then
sleep 5;
rm $1
elif [[ $(rm $1 | grep -m 1 'not found') ]] ; then
echo "file not found"
elif [[ $(rm $1 | grep -m 1 'You must have root access') ]] ; then
echo "You do not have root access"
else
echo "Incorrect parameter or command"
fi
}

Related

How to Ask User for Confirmation: Shell

I am new to shell, and my code takes two arguments from the user. I would like to confirm their arguments before running the rest of the code. I would like a y for yes to prompt the code, and if they type n for no, then the code will ask again for new arguments
Pretty much, if i type anything when I am asked to confirm, the rest of the code runs anyways. I tried inserting the rest of the code after the first then statement, but that didn't work either. I have also checked my code with ShellCheck and it all appears to be legal syntax. Any advice?
#!/bin/bash
#user passes two arguments
echo "Enter source file name, and the number of copies: "
read -p "Your file name is $1 and the number of copies is $2. Press Y for yes N for no " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "cloning files...."
fi
#----------------------------------------REST OF CODE
DIR="."
function list_files()
{
if ! test -d "$1"
then echo "$1"; return;
fi
cd ... || $1
echo; echo "$(pwd)":; #Display Directory name
for i in *
do
if test -d "$i" #if dictionary
then
list_files "$i" #recursively list files
cd ..
else
echo "$i"; #Display File name
fi
done
}
if [ $# -eq 0 ]
then list_files .
exit 0
fi
for i in "$#*"
do
DIR=$1
list_files "$DIR"
shift 1 #To read next directory/file name
done
if [ ! -f "$1" ]
then
echo "File $1 does not exist"
exit 1
fi
for ((i=0; i<$2; i++))
do
cp "$1" "$1$i.txt"; #copies the file i amount of times, and creates new files with names that increment by 1
done
status=$?
if [ "$status" -eq 0 ]
then
echo 'File copied succeaful'
else
echo 'Problem copying'
fi
Moving the prompts into a while loop might help here. The loop will re-prompt for the values until the user confirms them. Upon confirmation, the target code will be executed and the break statement will terminate the loop.
while :
do
echo "Enter source file name:"
read source_file
echo "Number of copies"
read number_of_copies
echo "Your file name is $source_file and the number of copies is $number_of_copies."
read -p "Press Y for yes N for no " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "cloning files...."
break ### <<<---- terminate the loop
fi
echo ""
done
#----------------------------------------REST OF CODE

Second subversion pre-commit hook not working

I am trying to add a second pre-commit script and it seems not to be catching when I place it in the hook.
The first script basically locks a file from being editing. The second script look at a path and compares a string value to a file that is being committed and if it matches then it will error.
#!/bin/sh
REPOS="$1"
TXN="$2"
GREP=/bin/grep
SED=/bin/sed
AWK=/usr/bin/awk
SVNLOOK=/usr/bin/svnlook
AUTHOR=`$SVNLOOK author -t "$TXN" "$REPOS"`
if [ "$AUTHOR" == "testuser" ]; then
exit 0
fi
if [ "$AUTHOR" == "" ]; then
exit 0
fi
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS" | $GREP "^[U|A]" | $AWK '{print $2}'`
COMPARE=`$SVNLOOK diff -t "$TXN" "$REPOS"`
#Operation 001 Beginning
#Restrict users from commiting against testfile
for PATH in $CHANGED
do
if [[ "$PATH" == *path/to/file/testfile.txt ]]; then
#allow testuser to have universal commit permissions in this path.
if [ "$AUTHOR" == "testuser" ]; then
exit 0
else
#User is trying to modify testfile.txt
echo "Only testuser can edit testfile.txt." 1>&2
exit 1
fi
fi
done
#Operation 001 Completed
#Operation 002 Beginning
#Restrict commits based on string found in file
for PATH in $COMPARE
do
if [[ "$PATH" == *path/to/look/at/only/* ]]; then
$SVNLOOK diff -t "$TXN" "$REPOS" | egrep 'string1|string2|string3' > /dev/null && { echo "Cannot commit using string1, string2 or string3 in files trying to commit" 1>&2; exit 1; }
else exit 0;
fi
done
#Operation 002 Completed
It keeps successfully committing the file even though the string is present. Any ideas why it wouldn't be catching it?
Your first test:
if [ "$AUTHOR" == "testuser" ]; then
exit 0
fi
It causes an abort (with zero exit value) if the AUTHOR is testuser!
So your second test:
if [ "$AUTHOR" == "testuser" ]; then
exit 0
else
#User is trying to modify testfile.txt
echo "Only testuser can edit testfile.txt." 1>&2
exit 1
fi
It's unnecessary because at this point the AUTHOR isn't testuser!
And maybe would better instead of your for-loop:
if $SVNLOOK changed -t "$TXN" "$REPOS" | $GREP "^[U|A]" | $AWK '{print $2}' | grep -q 'path/to/file/testfile.txt'; then
echo "Only testuser can edit testfile.txt." 1>&2
exit 1
fi
The if [[ "$PATH" == *path/to/file/testfile.txt ]]; then test doesn't work because this test doesn't understand shell variables (and would better enclose between quotation marks because of *).
And I would replace the
for PATH in $COMPARE
do
if [[ "$PATH" == *path/to/look/at/only/* ]]; then
part to
if echo ${COMPARE} | grep -q "path/to/look/at/only"; then

Strange syntax error in if condition - Shell Script

So I'm making a shell script in Ubuntu. It's purpose is simple. You give a command with arguments and you get a different operation each time. The problem is that when I run the the script it won't actually run because of a syntax error in one elif. The most suspicious thing is that I have a similar elif above wich works or at least doesn't pop a syntax error...
I'm leaving my code for you to see it and understand. Thanks in advance!
if [ "$1" = "-a" -a $# -lt 3 ]
then
echo "Add a new line in katalogos!"
read -p "Give me a name... " name
read -p "Give me a surname... " surname
read -p "Give me a city name... " cityName
read -p "Give me a phone number... " num
echo "$name $surname $cityName $num" > katalogos
elif [ "$1" = "-l" -a $# -lt 3 ]
then
echo "Content of katalogos will be sorted numerically and blank lines will be excluded!"
sort -b -n katalogos
elif [ "$1" = "-s" -a $# -lt 4 ]
if [[ $2 != *[!0-9]* ]]
then
echo "Content of katalogos will be sorted according to the second argument!"
sort +$3 katalogos
fi
elif [ "$1" = "-c" -a $# -lt 4 ] // syntax error
if [[ $2 = *[!0-9]* ]]
then
echo "Content of katalogos will be sorted according to the keyword!"
if [ $(grep -e "$2" katalogos | wc -l) -eq 0 ]
then
echo "String is not matched."
else
grep -e "$2" katalogos
fi
fi
elif [ "$1" = "-d" -a ( "$3" = "-b" -o "$3" = "-r" ) ]
if [[ $2 = *[!0-9]* ]]
then
echo "Katalogos's string matching lines will be deleted and blank lines will be in their place, assuming that the third argument equals -b, else just the lines will be deleted!"
if [ $(grep -e $2 katalogos | wc -l) -eq 0 ]
then
echo "String is not matched."
else
if [ "$3" = "-b" ]
then
sed -i "$3" katalogos | sed -i '$ a '
echo "A blank line inserted in place of the deleted one."
else
sed -i "$3" katalogos
echo "Line deleted."
fi
fi
fi
elif [ "$1" = "-n" ]
echo "katalogos's number of blank lines will be shown with the ability to delete them!"
grep -cvP '\S' katalogos
read -p "Do you want to delete them? Type 1 for yes or 0 for no... " ans
if [ $ans -eq 1 ]
then
grep -cvP '\S' file | sed -i
echo "Lines deleted."
fi
else
echo "Help centre!"
echo "-Type ./telcat -a to insert a new line to katalogos."
echo "-Type ./telcat -l to see the contents of katalogos sorted numerically (excluding blank lines)."
echo "-Type ./telcat -s plus a number to see the contents of katalogos sorted by the data that the number points to."
echo "-Type ./telcat -c plus a keyword to see only the lines that match with the word given."
echo "-Type ./telcat -d plus a keyword and -b or -r to delete the lines that contain the word given. Specifically if the third argument is -b it will automatically add a blank line to the deleted one and if it is -r it will not."
echo "-Type ./telcat -n to see the number of blank lines of katalogos."
echo "End of help centre!"
fi

unary operator expected with more than 1 argument

for var in "$#"
do
if test -z $var
then
echo "missing operand"
elif [ -d $var ]
then
echo "This is a directory"
elif [ ! -f $var ]
then
echo "The file does not exist"
else
basename=$(basename $var)
dirname=$(readlink -f $var)
inodeno=$(ls -i $var| cut -d" " -f1)
read -p "remove regular file $#" input
if [ $input = "n" ]
then exit 1
fi
mv $var "$var"_"$inodeno"
echo "$basename"_"$inodeno":"$dirname" >> $HOME/.restore.info
mv "$var"_"$inodeno" $HOME/deleted
fi
done
**Hello, the above code is trying to mimic the rm command in unix. Its purpose is to remove the file .
Eg if I type in bash safe_rm file1 , it works however if type in
bash safe_rm file1 file 2 , it prompts me to remove file 1 twice and gives me a unary operater expected for line 27(if [ $input = "n" ]).
Why does it not work for two files, ideally I would like it to prompt me to remove file1 and file 2.
Thanks
read -p "remove regular file $#" input
should probably be
read -p "remove regular file $var" input
That's the basic.
And this is how I'd prefer to do it:
for T in "$#"; do
if [[ -z $T ]]; then
echo "Target is null."
elif [[ ! -e $T ]]; then
echo "Target does not exist: $T"
elif [[ -d $T ]]; then
echo "Target can't be a directory: $T"
else
BASE=${T##*/}
DIRNAME=$(exec dirname "$T") ## Could be simpler but not sure how you want to use it.
INODE_NUM=$(exec stat -c '%i' "$T")
read -p "Remove regular file $T? "
if [[ $REPLY == [yY] ]]; then
# Just copied. Not sure about its logic.
mv "$T" "${T}_${INODE_NUM}"
echo "${BASE}_${INODE_NUM}:${DIRNAME}" >> "$HOME/.restore.info"
mv "${T}_${INODE_NUM}" "$HOME/deleted"
fi
fi
done

Strange behaviour of -d conditional expression

My KornShell (ksh) manual says that -d expression returns true if the file exists and it is a directory.
So if [[ -d file ]] should return TRUE if file is a directory. But in my case this is not how it works. It returns TRUE if the file exists and is NOT a directory, but the manual of the shells says "and it is a directory". So does anyone have any idea why it is working in the opposite of what it should be?
It's working fine; it's your expectations that are wrong. In shells, a 0 return value is true, and a non-zero return value is false.
$ true ; echo $?
0
$ false ; echo $?
1
ksh File Operator | True if:
-a | file exists
-d | file is a directory
-f | file is a regular file (i.e., not a directory or other special type of file)
-r | You have read permission on file
-s | file exists and is not empty
-w | You have write permission on file
-x | You have execute permission on file, or directory search permission if it is a directory
-O | file You own file
-G | file Your group ID is the same as that of file
kshFileOperatorsFunction.ksh
#***Function to demo ksh file Operators.***#
fileOperators(){
echo "Entering fileOperators function."
if [[ ! -a $1 ]]; then
print "file $1 does not exist."
return 1
fi
if [[ -d $1 ]]; then
print -n "$1 is a directory that you may "
if [[ ! -x $1 ]]; then
print -n "not "
fi
print "search."
elif [[ -f $1 ]]; then
print "$1 is a regular file."
else
print "$1 is a special type of file."
fi
if [[ -O $1 ]]; then
print 'you own the file.'
else
print 'you do not own the file.'
fi
if [[ -r $1 ]]; then
print 'you have read permission on the file.'
fi
if [[ -w $1 ]]; then
print 'you have write permission on the file.'
fi
if [[ -x $1 && ! -d $1 ]]; then
print 'you have execute permission on the file.'
fi
echo "Exiting fileOperators function."
}
Reference : O'Reilly, Learning the KornShell Volume 1

Resources