Shell Script Programs
https://bash.cyberciti.biz/guide/Main_Page
https://linuxconfig.org/bash-scripting-tutorial
Exit Status Shell Script Example
A simple shell script to locate username (finduser.sh)
#!/bin/bash
# set var
PASSWD_FILE=/etc/passwd
# get user name
read -p "Enter a user name : " username
# try to locate username in in /etc/passwd
grep "^$username" $PASSWD_FILE > /dev/null
# store exit status of grep
# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts
status=$?
if test $status -eq 0
then
echo "User '$username' found in $PASSWD_FILE file."
else
echo "User '$username' not found in $PASSWD_FILE file."
fi
Save and close the file. Run it as follows:
chmod +x finduser.sh
./finduser.sh
Sample Outputs:
Enter a user name : vivek User 'vivek' found in /etc/passwd file.
Run it again:
chmod +x finduser.sh
./finduser.sh
Sample Outputs:
Enter a user name : tommy
User 'tommy' not found in /etc/passwd file
Can I call a function of a shell script from another shell script?
I have 2 shell scripts.
The second shell script contains following functions second.sh
func1
func2
The first.sh will call the second shell script with some parameters and will call func1 and func2 with some other parameters specific to that function.
Refactor your
second.sh
script like this:function func1 {
fun=$1
book=$2
printf "fun=%s,book=%s\n" "${fun}" "${book}"
}
function func2 {
fun2=$1
book2=$2
printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}
And then call these functions from script
first.sh
like this:source ./second.sh
func1 love horror
func2 ball mystery
OUTPUT:
fun=love,book=horror
fun2=ball,book2=mystery
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home