BASH Scripting assistance needed - bash

Well, I am currently a novice shell scripter. I have a basic knowledge of other programming languages such as Javascript for HTML, JScript, VB.NET, and C++. (C++ Not so much, just dipped my feet in the water for that). Most recently, my recent project has been attempting to learn as much as I can about Bash shell scripting. The current issue is understanding status error codes, as well as checking if certain parameters contain directories or if it exists at all. I am working from a book, with tutorials and review questions. Unfortunately there is no answer key, or even hints for that matter.
Display an error message and exit with status 1 if no parameters are given
Display an error message and exit with status 2 if source is not a directory
Display an error message and exit with status 3 if destination does not exist or is not a directory
The above is what I must do, so far the first one I believe I have done correctly, if not please, correct me, or guide me in the proper direction. As I learn best when samples are given, I thought I would ask for assistance.
if [ $? ]; then
echo "You must supply at least one parameter"
exit 1
fi
#The above is the part I am pretty sure is correct.
if [ $? -d $directory "$1" ]; then
echo "$directory is not a directory"
exit 2
fi
#The above was self written. I am almost positive it is wrong.
if [ $? -lt 2 ]; then
set "$1" .pwd
fi
#the above was given to me from the book as a reference point to start (tutorial)

$? is the return code of a command you execute. Maybe you are thinking it's a return code of the current script. In any case it's not doing what you think it's doing.
All of my examples assume your command is run like so: script [source] [destination]
Error message if no parameters are given:
if [ ! "$#" ]; then
echo "please supply a parameter"
exit 1
fi
Display error if source is not a directory
if [ ! -d "$1" ]; then
echo "$1 is not a directory"
exit 2
fi
Display error if destination doesn't exist or isn't a directory
if [ ! -d "$2" ]; then
echo "$2 doesn't exist or isn't a directory"
exit 3
fi

Related

Why does $# always return 0?

I'm trying to write a script that will only accept exactly one argument. I'm still learning so I don't understand what's wrong with my code. I don't understand why, even though I change the number of inputs the code just exits. (Note: I'm going to use $dir for later if then statements but I haven't included it.)
#!/bin/bash
echo -n "Specify the name of the directory"
read dir
if [ $# -ne 1 ]; then
echo "Script requires one and only one argument"
exit
fi
You can use https://www.shellcheck.net/ to double check your syntax.
$# tells you how many arguments the script was called with.
Here you have two options.
Option 1: Use arguments
#!/bin/bash
if [[ $# -ne 1 ]]
then
echo "Script requires one and only one argument"
exit 1
else
echo "ok, arg1 is $1"
fi
To call the script do: ./script.bash argument
Use [[ ]] for testing conditions (http://mywiki.wooledge.org/BashFAQ/031)
exit 1: by default when a script exists with a 0 status code, it means it worked ok. Here since it is an error, specify a non-zero value.
Option 2: Do not use arguments, ask the user for a value.
Note: this version does not use arguments at all.
#!/bin/bash
read -r -p "Specify the name of the directory: " dir
if [[ ! -d "$dir" ]]
then
echo "Error, directory $dir does not exist."
exit 1
else
echo "ok, directory $dir exists."
fi
To call the script do: ./script.bash without any arguments.
You should research bash tutorials to learn how to use arguments.

Bash script for checking a value against line of values in a file

I have a script in Linux that will check a number inputted from the parameter. The number in this $status may vary. The script code after the is checking whether the code in $status is within a group of code or not. If yes, then echo "It exist". If not, then echo "Does not exist."
The problem is the group of code can change, and it's a pain to change the code conditional to reflect those changes. So I want to put all that group of numbers in a file.
For example:
The script check.sh:
$filecheck = "check.txt"
$status = $1
if [ $status EXISTS WITHIN $filecheck ]; then
echo "It exists."
else
echo "Does not exist."
fi
The check.txt contents:
201
5099
305
8670
2
582
9582
Run: # ./check.sh 305
Result: It exists.
Run: # ./check.sh 689
Result: Does not exist.
The question is, how should I formulate the conditional? I felt this should be not hard and involve grep, but I don't know how to formulate question about this in google to get the result I need, and I'm very beginner at bash script and Linux too. Actually the script is more than just this, but I only need the conditional part, so I simplified this down. Thanks.
Use grep:
if grep -q "$1" "$filecheck" >/dev/null 2>&1; then
echo "it exists"
else
echo "it does not exist"
fi
It doesn't look like a bash script but I think I got your question. You want to find if a given number exists in the list. To do that 'grep -w ...' should work for you, which looks for exact match. Note that it assumes that each number is on different line.
So your shell script would look like following:
filecheck="check.txt"
status=$1
grep -w $status $filecheck >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "It exists."
else
echo "Does not exist."
fi

Check for existance of directory always fails in Bash Script

I have a problem that has been bugging me for a few hours now. I have created a parameter --file-dir using getopt, which assigns a directory for the program to use. Following the parameter, the user has the choice to choose whatever directory they please. To keep the program stable, I check to see whether that directory even exists. The following code is what I have currently and it always returns "Directory does not exist. Terminating." even when I search for my /home directory.
-a|--file-dir) FILE_DIR=$2 ;
if [ ! -d "$FILE_DIR" ]; then
echo "Directory does not exist. Terminating." ;
exit 1;
else
echo "Directory exists." ;
fi ;
shift;;
Any input is much appreciated. The getopt's work fine with echo tests and such but fail when checking for directories.
It would be a good idea to check if you're really having the right argument for it:
-a|--file-dir) FILE_DIR=$2 ;
if [ ! -d "$FILE_DIR" ]; then
echo "Directory \"$FILE_DIR\" does not exist. Terminating." ;
exit 1;
else
echo "Directory exists." ;
fi ;
shift;;
If not certainly the problem is not in the checker but somewhere in your argument-parsing loop.
I had an issue with the same behavior: checking for a directory in the command line worked as expected, but always failed when done in a script.
I was running this script under git bash for Windows:
while read -r i; do
[ ! -d "$i" ] && echo "No $i"
done < "$1"
Windows' line endings (\r\n) can cause issues when splitting lines. Each test actually checks for directory\r instead of directory. Therefore, I needed to run the read command with the correct delimiter:
while IFS=$'\r\n' read -r i; do
It is possible that OP also had a similar issue, where non-printable characters got in the way.

Need some help writing an if statement in UNIX bash scripting

I'm writing a reasonably lengthy script (or what I would consider lengthy - you could probably do it in a few hours). I basically have a file (named .restore.info) which contains files of names. In part of the script, I want to test "If cannot find filename in .restore.info, then says “Error: restored file does not exist”. Apologies if this doesn't make sense for you guys (for me, it does in the grand scheme of things). So if type this in the command line:
sh MYSCRIPT filename
It will search for the string filename in the .restore.info file, and if it cant find anything, it should produce an error message.
Basically, I need the top line of this coded translated into a UNIX bash statement and something that actually makes sense!:
If grep $1 .restore.info returns an exist status of 1; then
echo “Filename does not exist!”
fi
Thanks in advance! Please ask me if you need me to clarify anything more clearly as I know I'm not the best explainer, and I'll get back to you in less than a minute! (+rep and best answer of course will be given!)
You probably only care if grep exits with a non-zero exit status:
if ! grep -q "$1" .restore.info; then
echo "Filename does not exist!"
fi
but if you really do care about a specific exit status (1, in this case):
if ! grep -q "$1" .restore.info && [[ $? -eq 1 ]]; then
echo "Filename does not exist!"
fi
Use grep -q
grep -q "filename" .restore.info && echo "found match"
or
! grep -q "filename" .restore.info && echo "not found"
grep -l 'filename' .restore.info
if [ $? = 0 ];then
echo "found it"
else
echo "not found"
fi

Bash- Using the 'find' command for testing

I want to know if there's any way to use the 'find' command in bash for testing. in other words, how do I go about making a conditional statement that tests whether a file was found with 'find' or not?
To expound more on what I mean, I've included the following code. The purpose of which should:
find a directory inputted by user
find a file in that directory, filename inputted by user
find a word in that file, which is also inputted by user
#!/bin/bash
#Task9.sh
cd /
echo "please enter a directory"
read direc
path= find home -depth -name "$direc"
if [ -z $path ]; then
echo "not a valid directory"
exit 1
else
cd $path
counter=3
while [ $counter -gt 0 ]; do
echo "enter a filename"
read FileName
FilePath= find $direc -depth -name "$FileName"
if [ -z $FilePath ]; then
break
else
let counter--
fi
done
if [ -z $FilePath ]; then
cd $FilePath
echo "input a word"
read SearchWord
echo "Found!"
grep $SearchWord $FileName
else
echo "No such file"
exit 2
fi
fi
exit 0
I'm very new to Bash, so I apologize for any easy mistakes I have overlooked. I'm not used to parsing the language yet. Thank you to anyone who helps me, it is greatly appreciated
you're using the find command plus the shell's -z $foo operator to figure out whether or not the user has specified the path to an existing file. There might be a way just to ask bash directly if the file exists or not, using a file-based operator, instead of running an unnecessary command and then using a string-based operator on the result (hint: there is). Some of the links on this page might help you:
http://tldp.org/LDP/abs/html/tests.html
good luck!

Resources