I have the following shell script :
#!/bin/sh
output=`./process_test.sh status_pid | grep "NOT STARTED: process_1" --line-buffered`
if[[ -z ${output} ]]
then
echo "process is not running"
else
echo "process is running"
fi
where ./process_test.sh status_pid is my utility for finding whether a process is running or not .e.g. if process_1 is not running it will give: NOT STARTED: process_1. Further
this utility is perfect and does not have any issue. I suspect the issue is with if syntax
on running this script I get the following output:
./test.sh: line 18: if[[ -z NOT: command not found
./test.sh: line 19: syntax error near unexpected token `then'
./test.sh: line 19: `then'
Can you help to resolve this issue?
You must use spaces to separate keywords such as if from the arguments or commands such as [[.
#!/bin/sh
output=$(./process_test.sh status_pid | grep -e "NOT STARTED: process_1" --line-buffered)
if [[ -z ${output} ]]
then
echo "process is not running"
else
echo "process is running"
fi
You should write it like
if [[ -z ${output} ]]
then
...
So you had missed a .
It would be a lot cleaner to write this:
#!/bin/sh
if ! ./process_test.sh status_pid |
grep "NOT STARTED: process_1" > /dev/null; then
echo "process is not running"
else
echo "process is running"
fi
Note that the --line-buffering argument is irrelevant, since
the pipe is not going to finish until after all of the input
is read. (Well, it's not totally irrelevant--it will make the
script run negligibly slower.)
Also note that '[[' is not standard. According to the shell language specification, it
"may be recognized as ( a ) reserved (word) on some implementations ..., causing unspecified results". In other words, it is what is commonly known as a "bashism" (although it is valid in shells other than bash), and if you use it you must not use #!/bin/sh as your interpreter, but should specify #!/bin/bash.
Related
I've got the following code in my shell script:
SERVER=`ps -ef | grep -v grep | grep -c sof2ded`
if ["$SERVER" != "0"]; then
echo "Already Running, exiting"
exit
else
echo "Starting up the server..."
cd /home/sof2/
/home/sof2/crons/start.sh > /dev/null 2>&1
fi
I did chmod a+x status.sh
Now I try to run the script but it's returning this error:
./status.sh: line 5: [1: command not found
Starting up the server...
Any help would be greatly appreciated.
Could you please try changing a few things in your script as follows and let me know if that helps you?(changed back-tick to $ and changed [ to [[ in code)
SERVER=$(ps -ef | grep -v grep | grep -c sof2ded)
if [[ "$SERVER" -eq 0 ]]; then
echo "Already Running, exiting"
exit
else
echo "Starting up the server..."
cd /home/sof2/
/home/sof2/crons/start.sh > /dev/null 2>&1
fi
The problem is with the test command. "But", I hear you say, "I am not using the test command". Yes you are, it is also known as [.
if statement syntax is if command. The brackets are not part of if syntax.
Commands have arguments separated (tokenized) by whitespace, so:
[ "$SERVER" != "0" ]
The whitespace is needed because the command is [ and then there are 4 arguments passed to it (the last one must be ]).
A more robust way of comparing numerics is to use double parentheses,
(( SERVER == 0 ))
Notice that you don't need the $ or the quotes around SERVER. Also the spacing is less important, but useful for readability.
[[ is used for comparing text patterns.
As a comment, backticks ` ` are considered deprecated because they are difficult to read, they are replaced with $( ... ).
I'm trying to write a shell script for Ubuntu, which checks the Teamspeak-server status and reacts to them.
This is my actual version:
a=$(sh /home/teamspeak3/ts3/teamspeak3-server_linux_amd64/ts3server_startscript.sh status)
echo "$a"
if [ "$a" -ne "Server is running"]
then
echo "..."
fi
exit 0
This is my actual output (and problem):
user1234#euve252903:~$ ./keepAlive.sh
Server is running
./keepAlive.sh: line 8: syntax error: unexpected end of file
(The text "Server is running" is the output from echo "$a").
I don't get the reason, why the syntax error appears...
I checked the file for MSDOS-ending signs.
Any ideas out there?
You're missing a space before the last bracket in your if statement
#!/bin/bash
a=$(sh /home/teamspeak3/ts3/teamspeak3-
server_linux_amd64/ts3server_startscript.sh status)
echo "$a"
if [ "$a" -ne "Server is running" ]; then
echo "..."
fi
exit 0
Also, I'd recommend adding a shebang and lastly, running the script in debug mode (bash -x) to find out what's wrong. If neither one of those work for you, try Shell Check, at least for syntax errors that is.
I am trying to create a simple bash script.
(just started working on bash scripting)
the script is simple. There is an issue with rsyslog service and from time to time dies.
I am trying to make a script to check if service is dead to restart it
till now I want to check if my conditions are ok but it seems I am getting an error. Can you advice me ?
Here is the script:
#!/bin/bash
a="dead"
b="running"
while i in $(/etc/init.d/rsyslog status | grep -o 'running\|dead');
do
if
[ "$a" == "$i" ];
then
echo "service rsyslog is dead "
if
[ "$b" == "$i" ];
then
echo "service rsyslog is running"
else
echo "nothing to do";
fi;
done
-------------
I am getting the following syntax error.
./rsyslogcheck.sh: line 17: syntax error near unexpected token done'
./rsyslogcheck.sh: line 17:done'
Thank you in advance!!
There are several problems here:
Invalid while loop syntax
Unnecessary loop: it seems you don't need a loop at all
Missing closing fi of an if that was opened
I suppose you're looking for something like this:
#!/bin/bash
status=$(/etc/init.d/rsyslog status | grep -o 'running\|dead')
case "$status" in
dead) echo "service rsyslog is dead";;
running) echo "service rsyslog is running";;
*) echo "nothing to do";;
esac
read -p "The Process running for "$days" days continuously OK to kill this process (y/N)? " -u 4 ok
[[ "${ok}" =~ y ]] || continue
echo "Killing $pid"
kill -HUP "$pid"
fi
This is the snippet of my script ,when i am executing this it shows like
`=~' is not expected.
How to resolve it?
I'm guessing your shebang line has #!/bin/sh and so you don't have access to the full ksh syntax. If you do, ksh93 does appear to support [[ string =~ regex ]] syntax, so there's something here which doesn't add up right.
Either way, there is a construct which works just as well in classic Bourne shell which you can use instead, with the added bonus that your script will be compatible to systems where ksh is not available.
You use read -p <prompt> but that is a Bashism; the -p option to read has a quite different meaning in ksh93.
printf 'Process ran for %i days continuously, OK to kill this? ' "$days"
read -u 4 ok
case $ok in [Yy]* ) ;; *) continue ;; esac
echo "Killing $pid"
kill -HUP "$pid"
Your code looked for y anywhere in the input but I restricted that to only examine the first character.
(Your code had erratic indentation and an unpaired fi which I omitted.)
Your ? is 'how to resolve' - tripleee's suggestion looks like a solution - simplify the code - try:
if [[ "${ok} == "y" ]]
I tried copying your code snippet and I get a different error. Time for D&C - simple ksh93 script testing '=~'
I am writing automated tests for the Gasoline, an OCaml library implementing application templates. Applications are expected to fail with a prescribed exit code in certain circumstances, like exit code 64 EXIT_USAGE when the application is called with an ill-formed command line:
% ./punishment.byte -x
punishment.byte: illegal option -- x
Usage: punishment.byte [-n number] [-p paragraph] [-c configfile]
Exit 64
Is there a standard Unix utility that can be used to run the subcommand ./punishment.byte -x and exit with status code 0 if the subcommand exited with status code 64? Something like
% expect_status 64 ./punishment.byte -x
punishment.byte: illegal option -- x
Usage: punishment.byte [-n number] [-p paragraph] [-c configfile]
Exit 0
As I am using a Makefile to orchestrate the tests, a legible statement such as expect_status 64 ./punishment.byte -x would be nice to have.
Notes
The Exit line in console interaction examples is informative and not part of the output.
I am well aware that I can write such a tool and how to do it, I just want to be sure there is no standard command doing that already.
The answer to your question is no. There is no standard utility on *nix systems for running a command and testing its exit code against a specific value. Probably because it's trivial to write one yourself.
I'm guessing from the % in your code that you're using zsh. If you're actually using csh (or tcsh), then things work differently.
That said, you can easily write a shell function to do this:
expect_status() {
local expected=$1
shift
"$#"
(( $? == expected ))
}
But that will run the command inside your current shell environment, which may have side effects you don't want. It would probably be better realized as a script - just save it somewhere in your $PATH with the filename expect_status and give it read and execute permission:
#!/bin/bash
expected=$1
shift
"$#"
(( $? == expected ))
Or, eschewing bashisms:
#!/bin/sh
expected=$1
shift
${1+"$#"}
[ $? -eq $expected ]
As suggested, you can check exit code of last command execution by referencing shell variable "$?".
$ ls -bogusOption
ls: invalid option -- 'O'
Try 'ls --help' for more information.
$ echo $?
2
shell can be used as utility to test exit code. say,
$ cat test.sh
#!/usr/bin/env bash
echo "executing bogus option"
ls -bogusOption
if [ "$?" -eq "0" ]; then
echo "command succeeded."
else
echo "command failed"
fi
$ bash -xv ./test.sh
#!/usr/bin/env bash
echo "executing bogus option"
+ echo 'executing bogus option'
executing bogus option
ls -bogusOption
+ ls -bogusOption
ls: invalid option -- 'O'
Try 'ls --help' for more information.
if [ "$?" -eq "0" ]; then
echo "command succeeded."
else
echo "command failed"
fi
+ '[' 2 -eq 0 ']'
+ echo 'command failed'
command failed
Well, in a sense, there is a standard utility: the shell itself:
command1 && command2
The above will only execute command2 if the exit code of command1 is 0. Alternatively, this:
command1 || command2
will only run command2 if the exit code of command1 was not 0.
To check for a specific exit status, you would use $? as described in the other answers:
command; [ "$?" -eq 64 ] && command2
So, the functionality you're looking for is essentially built directly into the shell and, therefore, you won't find a utility designed to do this.