How to pass error argument to next line in Makefile - makefile

For example, a Makefile is as below. There is only one target "Test".
Because "open" is not a valid command, the first line will come into error. How could I transfer this error information to the following conditional directive?
Test:
- open test.doc; ${foo} := $$?
ifeq (foo, 127)
echo "there is a fault"
else
echo "why?"
endif

By default, make will stop processing once a command return a non-zero status. You can change this by writing wrapper script, or by adding explicit SHELL commands to test the return code
Test:
- open test.doc ; foo=$$? ; \
if [ "$foo" = 127 ] ; then echo "There is a fault" ; else echo "Why ?" ; fi
Alternative:
Test:
- open test.doc ; \
if [ "$?" = 127 ] ; then echo "There is a fault" ; else echo "Why ?" ; fi

Related

bash script syntax error at function call and passing array as argument

I'm new to bash so assume that I don't understand everything in this simple script as I've been putting this together as of today with no prior experience with bash.
I get this error when I run test.sh:
command substitution: line 29: syntax error near unexpected token `$1,'
./f.sh: command substitution: line 29: `index_of($1, $urls))'
FILE: f.sh
#!/bin/bash
urls=( "example.com" "example2.com")
error_exit()
{
echo "$1" 1>&2
exit 1
}
index_of(){
needle=$1
haystack=$2
for i in "${!haystack[#]}"; do
if [[ "${haystack[$i]}" = "${needle}" ]]; then
echo "${i}"
fi
done
echo -1
}
validate_url_param(){
index=-2 #-2 as flag
if [ $# -eq 0 ]; then
error_exit "No url provided. Exiting"
else
index=$(index_of($1, $urls)) #ERROR POINTS TO THIS LINE
if [ $index -eq -1 ]; then
error_exit "Provided url not found in list. Exiting"
fi
fi
echo $index
}
FILE: test.sh
#!/bin/bash
. ./f.sh
index=$(validate_url_param "example.com")
echo $index
echo "${urls[0]}"
I've lost track of all of the tweaks I tried but google is failing me and I'm sure this is some basic stuff so... thanks in advance.
The immediate error, just like the error message tells you, is that shell functions (just like shell scripts) do not require or accept commas between their arguments or parentheses around the argument list. But there are several changes you could make to improve this code.
Here's a refactored version, with inlined comments.
#!/bin/bash
urls=("example.com" "example2.com")
error_exit()
{
# Include script name in error message; echo all parameters
echo "$0: $#" 1>&2
exit 1
}
# A function can't really accept an array. But it's easy to fix:
# make the first argument the needle, and the rest, the haystack.
# Also, mark variables as local
index_of(){
local needle=$1
shift
local i
for ((i=1; i<=$#; ++i)); do
if [[ "${!i}" = "${needle}" ]]; then
echo "${i}"
# Return when you found it
return 0
fi
done
# Don't echo anything on failure; just return false
return 1
}
validate_url_param(){
# global ${urls[#]} is still a bit of a wart
if [ $# -eq 0 ]; then
error_exit "No url provided. Exiting"
else
if ! index_of "$1" "${urls[#]}"; then
error_exit "Provided url not found in list. Exiting"
fi
fi
}
# Just run the function from within the script itself
validate_url_param "example.com"
echo "${urls[0]}"
Notice how the validate_url_param function doesn't capture the output from the function it is calling. index_of simply prints the result to standard output and that's fine, just let that happen and don't intervene. The exit code tells us whether it succeeded or not.
However, reading the URLs into memory is often not useful or necessary. Perhaps you are simply looking for
grep -Fx example.com urls.txt

Shell if else fi syntax error while actual syntax seems correct

So I have a shell script that contains a big if/fi block, and it was working fine until I decided to place an else case for this big if/fi block. Now I am getting this error:
/root/VVPN/Scripts/scriptPrincipal.sh: line 201: syntax error near unexpected token `else'
/root/VVPN/Scripts/scriptPrincipal.sh: line 201: `else'
I went through 8~10 stackoverflow posts where people had exactly the same error, except that all of them were simple syntax errors like a missing space after the [ of the if statement, or a : instead of a ; before the then keyword, or an else intended for an if that was already closed with a fi, etc... (you get the idea :p).
However I've checked my code for all these errors over and over and everything seems to be correct when it comes to if/else/fi syntax. I even showed the code to some colleagues and they too couldn't find the reason for this error.
Here's the code:
if [ ${CP} != "continue" ]
then
echo 'Downloading the necessary files from the server...'
# If folder F*** doesn't exist in /root/VVPN/Numbers
if [ ! -d ${N} ]
then
# Create folders F***, and F***/Results
mkdir ${N}
mkdir ${N}/Results
cd ${N}
# Get real number to factorize from server (e.g: wget server.com:8000/route/to/F1067/F1067)
ROUTE="VVPN/Numbers/${N}/${N}"
REAL_NUM_FILENAME=${N}
while true
do
wget --retry-connrefused --tries=inf -q ${SERVER}/${ROUTE} -O ${REAL_NUM_FILENAME} --continue
if [ $? -eq 0 ]; then
break
fi
sleep 1
done
# Get ECM-Program tuned for this number from server (e.g: wget server.com:8000/route/to/F1067/ecm)
ROUTE="VVPN/Numbers/${N}/ecm"
PROGRAM_NAME='ecm'
while true
do
wget --retry-connrefused --tries=inf -q ${SERVER}/${ROUTE} -O ${PROGRAM_NAME} --continue
if [ $? = 0 ]; then
break
fi
sleep 1
done
else
# The folder already exists, now we have to check whether the number has ",c" label or not
cd ${N}
fi
# Give the permission to execute program
chmod +x ecm
# Make 6 directories, one for each SPE
for i in {1..6}
do
mkdir "SPE${i}"
cp ecm "SPE${i}/"
done
# if there is no checkpoints:
if [ $CP = $N ]
then
# Get currentSigma for this number from server (e.g : wget server.com:8000/rout/to/F1067/currentSigma.txt)
ROUTE="VVPN/Numbers/${N}/currentSigma"
REAL_FILE_NAME='sigma'
while true
do
wget --retry-connrefused --tries=inf -q ${SERVER}/${ROUTE} -O ${REAL_FILE_NAME} --continue
if [ $? = 0 ]; then
break
fi
sleep 1
done
else
#The number has a ",c" label (= w/ checkpoint)
# Get i (server sigma) and C (current job counter) from the server (e.g: wget server.com:8000/route/to/F1067/icy)
ROUTE="icy?number=${N}"
SIGMA_C_Y='icy'
while true
do
wget --retry-connrefused --tries=inf -q ${SERVER}/${ROUTE} -O ${SIGMA_C_Y} --continue
if [ $? = 0 ]; then
break
fi
sleep 1
done
i=$(cat ${SIGMA_C_Y} | cut -d "," -f1)
C=$(cat ${SIGMA_C_Y} | cut -d "," -f2)
Y=$(cat ${SIGMA_C_Y} | cut -d "," -f3)
echo $i > sigma
echo $C > /root/VVPN/Scripts/C
# Get the checkpoints from the server
ROUTE="VVPN/Numbers/${N}/CP/${i},${C},${Y}"
for speNum in {1..6}
do
SPE="SPE${speNum}"
touch $SPE/again
for bigX in {0..3}
do
CHECKPOINT="pointsCurve${bigX}.${Y}"
while true
do
wget --retry-connrefused --tries=inf -q ${SERVER}/${ROUTE}/${SPE}/${CHECKPOINT} -O ${CHECKPOINT} --continue
if [ $? = 0 ]; then
mv $CHECKPOINT $SPE
break
fi
sleep 1
done
done
done
fi
cd ..
else
echo "Found ${N}'s folder on this PS3"
fi
So the else mentioned in the error (at line 201) is actually the last else in the code. The script works fine without this else and the echo that comes right after.
Any help would be much appreciated :)
Could you change if [ $CP = $N ] as below;
if [ "$CP" == "$N" ]
This is not if else problem; For example; if you run the following code, output is same. So You should focus other commands inside if statement.
CP="continue1"
if [ ${CP} != "continue" ]
then
while #this is wrong
echo ok
echo ok
echo ok
else
fi
./test.sh: line 8: syntax error near unexpected token `else'
./test.sh: line 8: `else'

bash syntax error in OSX

The following bash script, written and tested on Linux, does not even start on OS X when called.
#!/bin/bash
#
# Some comments
#
#
function usage {
echo ""
echo "Usage: thisscript <SOURCE_DIRECTORY> <TARGET_DIRECTORY>"
echo ""
echo "<SOURCE_DIRECTORY> the directory where the this "
echo " directory resides (default is /usr/dis)"
echo ""
echo "<TARGET_DIRECTORY> the destination directory"
echo ""
}
function notDarwin {
mv -f $CUR_DIR/* $NEW_DIR/
ln -sf "$NEW_DIR/ee/sc/scrp" "/usr/bin/scrp"
ln -sf "$NEW_DIR/ee/etc/conffile.conf" "/etc/conffile.conf"
exit 0
}
function isDarwin {
mv -f $CUR_DIR/* $NEW_DIR/
ln -sf "$NEW_DIR/ee/sc/scrp" "/usr/local/bin/scrp"
cp "$NEW_DIR/ee/etc/conffile.conf" "/etc/conffile.conf"
exit 0
}
#
# =============================================
# ================== MAIN =====================
# =============================================
#
CUR_DIR=${1%/}
NEW_DIR=${2%/}
if [ ! -d "$CUR_DIR" ]; then
echo ""
echo "blah blah"
usage
exit 1
fi
if [ ! -d "$NEW_DIR" ]; then
echo ""
echo "The target directory supplied does not exist. Creating target directory $NEW_DIR"
mkdir "$NEW_DIR"
if [ $? -ne 0 ]; then
echo "Could not create target directory. Exiting..."
exit 1
else
echo "Directory $NEW_DIR created"
fi
echo ""
fi
UNAME=$(uname)
if [ $UNAME == "Darwin" ]; then
isDarwin
else
notDarwin
fi
It throws the following syntax error when run as sudo bash script.sh "arg1" "arg2" on macOS with bash 3.2
'script.sh: line 7: syntax error near unexpected token `{
'script.sh: line 7: `function usage {
I am rather new to OS X, maybe there is a gotcha I am missing. The script ran fine on Linux...
Thanks
Linux and modern OS X expect lines to end with LF (line feed) characters. If your lines end with CR + LF, then you will run into problems.
Some other general pointers:
The function syntax is non-standard. You should use the standard syntax, supported by all POSIX-compliant shells:
Change:
function usage {
to:
usage() {
and I suspect that all will be well.
As an aside, you should quote all of your parameter expansions (you've missed a couple). It's also considered good practice to use lowercase variable names, as uppercase ones are used by the shell and you run the risk of clashing with them.

Makefile: capture error code in rule, ignore error, take decision based on error code

So, I currently have this:
TEST = "?"
oktest:
#-/bin/false && ([ $$? -eq 0 ] && echo "success!") || true; $(eval TEST = "all ok")
#echo $(TEST)
badtest:
#-/bin/false && ([ $$? -eq 0 ] && echo "success!") || true; $(eval TEST = "got error")
#echo $(TEST)
#T=echo;if [ $(TEST) = "got error" ]; then \
echo "some error detected, cleanup env and fail test"; \
/bin/false; \
fi
all: oktest badtest
As you can see, its based on:
ignoring error codes ("-" and "|| true", both will do, but I prefer this way)
doing run-time comparison with shell code.
aborting with shell command returning false.
Is there a way to make it shorter, save returned error code and compare it to known values in runtime - without falling back to embedded shell code or external scripts?

unix construct "or" condition on a filename

I have a shell script where I pass (2) parameters, one to pass a dbname, the other to call one of (2) filenames. I want to check if either filename exists, then proceed with calling that script, else exit because the user can enter the wrong string and construct my_foo.sql which I don't want. I don't think I have the condition for setting "or" correctly since putting the correct param still produces error. Is there a better way to write this?
Here is what I have so far.
#/usr/bin/ksh
if [ $# != 2 ]; then
echo "Usage: test.sh <dbname> <test|live>" 2>&1
exit 1
fi
# Check actual file name
CHKSCRIPT1=/tmp/my_test.sql;
CHKSCRIPT2=/tmp/my_live.sql;
if [ -f "CHKSCRIPT1" ] || [ -f "CHKSCRIPT2" ]
then
/bin/sqlplus -s foo/bar #/my_$2.sql
else
echo "Correct sql script does not exist. Enter test or live"
exit 1
fi
Your issue is that you're not referencing your variables correctly:
if [ -f "$CHKSCRIPT1" ] || [ -f "$CHKSCRIPT2" ]
...
fi
edit: Per #chepner, you shouldn't use -o
In addition to the problem you had with expanding the parameters, you should separate what the user types from what files need to exist. If the user enters "live", the only thing that matters is whether or not /tmp/my_live.sql exists. If the user enters "injection_attack", your script should not execute /tmp/my_injection_attack.sql (which presumably was created without your knowledge). The right thing to do is to first verify that a valid command was entered, then check if the appropriate file exists.
if [ $# != 2 ]; then
echo "Usage: test.sh <dbname> <test|live>" 2>&1
exit 1
fi
case $2 in
test|live)
filename="/tmp/my_{$2}.sql"
;;
*) echo "Must enter test or live"
exit 1
;;
esac
if [ -f "$filename" ]; then
/bin/sqlplus -s foo/bar #/my_$2.sql
else
echo "SQL script $filename does not exist."
exit 1
fi

Resources