Run wget and other commands in shell script - bash

I'm trying to create a shell script that I will download the latest Atomic gotroot rules to my server, unpack them, copy them to the correct folder, etc.,
I've been reading shell tutorials and forum posts for most of the day and the syntax escapes me for some of these. I have run all these commands and I know they work if I manually run them.
I know I need to develop some error checking, but I'm just trying to get the commands to run correctly. The main problem at the moment is the syntax of the wget commands, i've got errors about missing semi-colons, divide by zero, unsupported schemes - I've tried various quoting (single and double) and escaping - / " characters in various combinations.
Thanks for any help.
The raw wget command is
wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"
#!/bin/sh
update_modsec_rules(){
wget=/usr/bin/wget
tar=/bin/tar
apachectl=/usr/bin/apache2ctl
TXT="Script Run Finished"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES="/var/asl/updates/modsec/*"
EXISTING_ARCH="/var/asl/updates/modsec-*"
WGET_OPTS='--user=jim --password=xxx-yyy-zzz'
URL_BASE="http://updates.atomicorp.com/channels/rules/subscription"
# change to working directory and cleanup any downloaded files and extracted rules in modsec/ directory
cd $WORKING_DIR
rm -f $EXISTING_ARCH
rm -f $EXISTING_FILES
rm -f VERSION*
# wget to download VERSION file
$wget ${WGET_OPTS} "${URL_BASE}/VERSION"
# get current MODSEC_VERSION from VERSION file and save as variable
source VERSION
TARGET_DATE=$MODSEC_VERSION
echo $TARGET_DATE
# wget to download current archive
$wget ${WGET_OPTS} "${URL_BASE}/modsec-${TARGET_DATE}.tar.gz"
# extract archive
echo "extracting files . . . "
tar zxvf $WORKING_DIR/modsec-${TARGET_DATE}.tar.gz
echo "copying files . . . "
cp -uv $EXISTING_FILES $TARGET_DIR
echo $TXT
}
update_modsec_rules $# 2>&1 | tee -a /var/asl/modsec_update.log
RESTART_APACHE="/usr/local/cpanel/scripts/restartsrv httpd"
$RESTART_APACHE

Here are some guidelines to use when writing shell scripts.
Always quote variables when you use them. This helps avoid the possibility of misinterpretation. (What if a filename contains a space?)
Don't trust fileglobbing on commands like rm. Use for loops instead. (What if a filename starts with a hyphen?)
Avoid subshells when possible. Your lines with backquotes make me itchy.
Don't exec if you can help it. And especially don't expect any parts of your script after your exec to actually get run.
I should point out that while your shell may be bash, you've specified /bin/sh for execution of this script, so it is NOT a bash script.
Here's a rewrite with some error checking. Add salt to taste.
#!/bin/sh
# Linux
wget=/usr/bin/wget
tar=/bin/tar
apachectl=/usr/sbin/apache2ctl
# FreeBSD
#wget=/usr/local/bin/wget
#tar=/usr/bin/tar
#apachectl=/usr/local/sbin/apachectl
TXT="GOT TO THE END, YEAH"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES_DIR="/var/asl/updates/modsec/"
EXISTING_ARCH="/var/asl/updates/"
URL_BASE="http://updates.atomicorp.com/channels/rules/subscription"
WGET_OPTS='--user="jim" --password="xxx-yyy-zzz"'
if [ ! -x "$wget" ]; then
echo "ERROR: No wget." >&2
exit 1
elif [ ! -x "$apachectl" ]; then
echo "ERROR: No apachectl." >&2
exit 1
elif [ ! -x "$tar" ]; then
echo "ERROR: Not in Kansas anymore, Toto." >&2
exit 1
fi
# change to working directory and cleanup any downloaded files
# and extracted rules in modsec/ directory
if ! cd "$WORKING_DIR"; then
echo "ERROR: can't access working directory ($WORKING_DIR)" >&2
exit 1
fi
# Delete each file in a loop.
for file in "$EXISTING_FILES_DIR"/* "$EXISTING_ARCH_DIR"/modsec-*; do
rm -f "$file"
done
# Move old VERSION out of the way.
mv VERSION VERSION-$$
# wget1 to download VERSION file (replaces WGET1)
if ! $wget $WGET_OPTS $URL_BASE}/VERSION; then
echo "ERROR: can't get VERSION" >&2
mv VERSION-$$ VERSION
exit 1
fi
# get current MODSEC_VERSION from VERSION file and save as variable,
# but DON'T blindly trust and run scripts from an external source.
if grep -q '^MODSEC_VERSION=' VERSION; then
TARGET_DATE="`sed -ne '/^MODSEC_VERSION=/{s/^[^=]*=//p;q;}' VERSION`"
echo "Target date: $TARGET_DATE"
fi
# Download current archive (replaces WGET2)
if ! $wget ${WGET_OPTS} "${URL_BASE}/modsec-$TARGET_DATE.tar.gz"; then
echo "ERROR: can't get archive" >&2
mv VERSION-$$ VERSION # Do this, don't do this, I don't know your needs.
exit 1
fi
# extract archive
if [ ! -f "$WORKING_DIR/modsec-${TARGET_DATE}.tar.gz" ]; then
echo "ERROR: I'm confused, where's my archive?" >&2
mv VERSION-$$ VERSION # Do this, don't do this, I don't know your needs.
exit 1
fi
tar zxvf "$WORKING_DIR/modsec-${TARGET_DATE}.tar.gz"
for file in "$EXISTING_FILES_DIR"/*; do
cp "$file" "$TARGET_DIR/"
done
# So far so good, so let's restart apache.
if $apachectl configtest; then
if $apachectl restart; then
# Success!
rm -f VERSION-$$
echo "$TXT"
else
echo "ERROR: PANIC! Apache didn't restart. Notify the authorities!" >&2
exit 3
fi
else
echo "ERROR: Apache configs are broken. We're still running, but you'd better fix this ASAP." >&2
exit 2
fi
Note that while I've rewritten this to be more sensible, there is certainly still a lot of room for improvement.

You have two options:
1- changing this to
WGET1=' --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"'
then run
wget $WGET1 same to WGET2
Or
2- encapsulating $WGET1 with backquotes ``.
e.g.:
`$WGET`
This applies to any command your executing out of a variable.
Suggested changes:
#!/bin/sh
TXT="GOT TO THE END, YEAH"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES="/var/asl/updates/modsec/*"
EXISTING_ARCH="/var/asl/updates/modsec-*"
WGET1='wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"'
WGET2='wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/modsec-$TARGET_DATE.tar.gz"'
## change to working directory and cleanup any downloaded files and extracted rules in modsec/ directory
cd $WORKING_DIR
rm -f $EXISTING_ARCH
rm -f $EXISTING_FILES
## wget1 to download VERSION file
`$WGET1`
## get current MODSEC_VERSION from VERSION file and save as variable
source VERSION
TARGET_DATE=`echo $MODSEC_VERSION`
## WGET2 command to download current archive
`$WGET2`
## extract archive
tar zxvf $WORKING_DIR/modsec-$TARGET_DATE.tar.gz
cp $EXISTING_FILES $TARGET_DIR
## restart server
exec '/usr/local/cpanel/scripts/restartsrv_httpd' $*;
Pro Tip: If you need string substitution, using ${VAR} is much better to eliminate ambiguity, e.g.:
tar zxvf $WORKING_DIR/modsec-${TARGET_DATE}.tar.gz

Related

Getting test: too many arguments error while checking existence of directory in shell script

I am trying to write a shell script for extraction of .tar.gz file. I need to check first that if same directory is not present then extract the zip file. Otherwise do some thing else. Below is my shell script.
#!/bin/bash
INSTALL_DIR=$HOME/Test/LogShipper
LOGSTASH_PATH=logstash-2.3.2
LOGSTASH_FOLDER=$HOME/Test/LogShipper/logstash
LOGSTASH_BINARY=$LOGSTASH_PATH.tar.gz
ES_PATH=elasticsearch-2.3.2
ES_BINARY=$ES_PATH.tar.gz
KIBANA_VERSION=kibana-4.5.0
KIBANA_OS=darwin-x64
KIBANA_BINARY=$KIBANA_VERSION-$KIBANA_OS
echo Installing ELK stack into $INSTALL_DIR
mkdir -p $INSTALL_DIR
cd $INSTALL_DIR
if test [! -d "$LOGSTASH_FOLDER" ];
then
if test -s $LOGSTASH_BINARY
then
echo Logstash Zip Exists
echo Now installing...
echo Unpacking logstash...
tar zxf $LOGSTASH_BINARY $LOGSTASH_FOLDER
echo Unpacking Completed.
else
echo Downloading logstash 2.3.2
curl -O https://download.elasticsearch.org/logstash/logstash/$LOGSTASH_BINARY
fi
else
echo Logstash already installed.
fi
I am getting error test: too many arguments at line if test [! -d "$LOGSTASH_FOLDER" ];
You probably don't need to use test when using [] as it implicitly invokes the same during evaluation. Also include a space after open brace [.
if [ ! -d "$LOGSTASH_FOLDER" ];
You can explicitly use test command the following way, try
if ! test -d "$LOGSTASH_FOLDER"
If "$HOME" has any spaces in it, and were unquoted (as it is in the given code), that would cause the error in question. Suggest changing:
INSTALL_DIR=$HOME/Test/LogShipper
...
LOGSTASH_FOLDER=$HOME/Test/LogShipper/logstash
...
mkdir -p $INSTALL_DIR
...
cd $INSTALL_DIR
To:
INSTALL_DIR="$HOME"/Test/LogShipper
...
LOGSTASH_FOLDER="$HOME"/Test/LogShipper/logstash
...
mkdir -p "$INSTALL_DIR"
...
cd "$INSTALL_DIR"

Passing a path as an argument to a shell script

I've written bash script to open a file passed as an argument and write it into another file. But my script will work properly only if the file is in the current directory. Now I need to open and write the file that is not in the current directory also.
If compile is the name of my script, then ./compile next/123/file.txt should open the file.txt in the passed path. How can I do it?
#!/bin/sh
#FIRST SCRIPT
clear
echo "-----STARTING COMPILATION-----"
#echo $1
name=$1 # Copy the filename to name
find . -iname $name -maxdepth 1 -exec cp {} $name \;
new_file="tempwithfile.adb"
cp $name $new_file #copy the file to new_file
echo "compiling"
dir >filelist.txt
gcc writefile.c
run_file="run_file.txt"
echo $name > $run_file
./a.out
echo ""
echo "cleaning"
echo ""
make clean
make -f makefile
./semantizer -da <withfile.adb
Your code and your question are a bit messy and unclear.
It seems that you intended to find your file, given as a parameter to your script, but failed due to the maxdepth.
If you are given next/123/file.txt as an argument, your find gives you a warning:
find: warning: you have specified the -maxdepth option after a
non-option argument -iname, but options are not positional (-maxdepth
affects tests specified before it as well as those specified after
it). Please specify options before other arguments.
Also -maxdepth gives you the depth find will go to find your file until it quits. next/123/file.txt has a depth of 2 directories.
Also you are trying to copy the given file within find, but also copied it using cp afterwards.
As said, your code is really messy and I don't know what you are trying to do. I will gladly help, if you could elaborate :).
There are some questions that are open:
Why do you have to find the file, if you already know its path? Do you always have the whole path given as an argument? Or only part of the path? Only the basename ?
Do you simply want to copy a file to another location?
What does your writefile.c do? Does it write the content of your file to another? cp does that already.
I also recommend using variables with CAPITALIZED letters and checking the exit status of used commands like cp and find, to check if these failed.
Anyway, here is my script that might help you:
#!/bin/sh
#FIRST SCRIPT
clear
echo "-----STARTING COMPILATION-----"
echo "FILE: $1"
[ $# -ne 1 ] && echo "Usage: $0 <file>" 1>&2 && exit 1
FILE="$1" # Copy the filename to name
FILE_NEW="tempwithfile.adb"
cp "$FILE" "$FILE_NEW" # Copy the file to new_file
[ $? -ne 0 ] && exit 2
echo
echo "----[ COMPILING ]----"
echo
dir &> filelist.txt # list directory contents and write to filelist.txt
gcc writefile.c # ???
FILE_RUN="run_file.txt"
echo "$FILE" > "$FILE_RUN"
./a.out
echo
echo "----[ CLEANING ]----"
echo
make clean
make -f makefile
./semantizer -da < withfile.adb

bad character showing up in bash script execution

I have a bash script that is getting an accented character appended to some strings that is causing it to fail, and I can't find where or how these characters are getting in there.
Here is some example output:
mv: cannot move â/tmp/myapp.zipâ to â/opt/myserver/myapp/deploys/myapp.1.2.21.zipâ: No such file or directory
ln: failed to create symbolic link â/opt/myserver/myapp/deploys/myapp_beta.zipâ: No such file or directory
cp: cannot stat â/opt/myserver/myapp/deploys/myapp_beta.zipâ: No such file or directory
the invalid character is the â.
The script is below:
#!/bin/bash
BRANCH=$1
SVN_LOC="https://svn/svn/myserver/"
MYAPP_REPO="myapp.git"
COREJS_REPO="core-js.git"
SPARTAN_REPO="core-spartan.git"
MYAPP_LOCATION="myapp/"
COREJS_LOCATION="corejs/"
SPARTAN_LOCATION="spartan/"
DEPLOY_LOCATION="/tmp/deploy/"
CLEANUP="${DEPLOY_LOCATION}*"
DEPLOY_STORE="/opt/myserver/myapp/deploys/"
DEPLOY_TIME=$(date +%s)
failed ()
{
rm -rf $CLEANUP
exit 1
}
mkdir -p $DEPLOY_LOCATION
echo "Retrieving Code from Git Branch ${BRANCH}"
echo "Retrieving myapp code"
mkdir -p "${DEPLOY_LOCATION}${MYAPP_LOCATION}"
pushd /opt/myserver/myapp/myapp
git archive $BRANCH | tar -x -C "${DEPLOY_LOCATION}${MYAPP_LOCATION}"
if [ $? -ne 0 ]
then
echo "Failed retrieving code from git ${MYAPP_REPO} repo";
failed
fi
popd
echo "Checking version numbers"
VERSION=$(php "${DEPLOY_LOCATION}${MYAPP_LOCATION}version.php" output)
DEPLOY_PACKAGE="${DEPLOY_STORE}myapp.${VERSION}.zip"
if [ -f $DEPLOY_PACKAGE ]
then
echo "A deploy with the same version number (${VERSION}) already exists! Please increment version number or manually deal with existing ${DEPLOY_PACKAGE}";
failed
fi
echo "Retrieving corejs code"
mkdir -p "${DEPLOY_LOCATION}${COREJS_LOCATION}"
pushd /opt/myserver/myapp/core-js
git archive $BRANCH | tar -x -C "${DEPLOY_LOCATION}${COREJS_LOCATION}"
if [ $? -ne 0 ]
then
echo "Failed retrieving code from git ${COREJS_REPO} repo";
failed
fi
popd
echo "Retrieving spartan code"
mkdir -p "${DEPLOY_LOCATION}${SPARTAN_LOCATION}"
pushd /opt/myserver/myapp/spartan
git archive $BRANCH | tar -x -C "${DEPLOY_LOCATION}${SPARTAN_LOCATION}"
if [ $? -ne 0 ]
then
echo "Failed retrieving code from git ${SPARTAN_REPO} repo";
failed
fi
popd
echo "Minifying js and css"
pushd "${DEPLOY_LOCATION}${MYAPP_LOCATION}Server/Deploy/"
php MinifyLyroke.php --deploytime $DEPLOY_TIME
popd
ASSETS_DEPLOY_PACKAGE="${DEPLOY_STORE}myappassets.${VERSION}.zip"
TEMP_ASSETS_ZIP_LOC="/tmp/myappassets.zip"
DEPLOY_ASSETS="${DEPLOY_LOCATION}myapp/Assets/"
ASSETS_DEPLOY_LOCATION="/tmp/assetsdeploy/"
DEPLOYED_ASSETS="${ASSETS_DEPLOY_LOCATION}myappassets_${DEPLOY_TIME}"
mkdir -p $ASSETS_DEPLOY_LOCATION
echo "Packaging assets deploy to ${ASSETS_DEPLOY_PACKAGE}"
mv $DEPLOY_ASSETS $DEPLOYED_ASSETS
pushd $ASSETS_DEPLOY_LOCATION
zip -r ${TEMP_ASSETS_ZIP_LOC} *
popd
mv ${TEMP_ASSETS_ZIP_LOC} ${ASSETS_DEPLOY_PACKAGE}
ln -sfn ${ASSETS_DEPLOY_PACKAGE} "${DEPLOY_STORE}myappassets_beta.zip"
cp "${DEPLOY_STORE}myappassets_beta.zip" "/opt/myserver/myapp/myapp/Server/Deploy/"
rm -rf $DEPLOYED_ASSETS
rm -rf $ASSETS_DEPLOY_LOCATION
echo "Packaging deploy to ${DEPLOY_PACKAGE}"
TEMP_ZIP_LOC="/tmp/myapp.zip"
pushd ${DEPLOY_LOCATION}
zip -r ${TEMP_ZIP_LOC} *
popd
mv "${TEMP_ZIP_LOC}" "${DEPLOY_PACKAGE}"
ln -sfn "${DEPLOY_PACKAGE}" "${DEPLOY_STORE}myapp_beta.zip"
cp "${DEPLOY_STORE}myapp_beta.zip" "/opt/myserver/myapp/myapp/Server/Deploy"
echo "Cleaning up"
rm -rf $CLEANUP
can anyone possibly see the issue or suggest a way I can go about finding where the issue is?
Those â characters are just mangled smart quotes printed from your shell. Your shell is probably outputting UTF-8, but your terminal is reading ISO-8859-1. Note that â is the rendering of a UTF-8 encoded smart quote ‘ in ISO-8859-1, with two nonprintable characters following the â. Most modern terminal emulators come with an option to enable UTF-8; see if you can enable that (it will make your life easier).
The problem is in your script, not the funny characters.
Try opening the script in another text editor like Notepad++ and see if there are any special characters present.
From the command line, type both of these commands. One or more of the files/directories you are expecting to exist, does not exist.
ls /tmp/myapp.zip
ls /opt/myserver/myapp/deploys
The accepted answer explains the problem, thanks #nneonneo. This is what you can do for a quick fix:
A) check your locale settings with:
locale
B) before calling your script or in the top of your bash-script try:
export LANG=en_US.UTF-8
export LC_ALL=C

Shell script file existence on Mac issue

Ok so I have written a .sh file in Linux Ubuntu and it works perfectly. However on a Mac it always returns that the file was not found even when it is in the same directory. Can anyone help me out?
.sh file:
if [ ! -f file-3*.jar ]; then
echo "[INFO] jar could not be found."
exit
fi
Just thought I'd add, this isn't for more than one file, it's for a file that is renamed to multiple endings.
In a comment to #Paul R's answer, you said "The shell script is also in the same directory as the jar file. So they can just double click it after assigning SH files to open with terminal by default." I suspect that's the problem -- when you run a shell script by double-clicking it, it runs with the working directory set to the user's home directory, not the directory where the script's located. You can work around this by having the script cd to the directory it's in:
cd "$(dirname "$BASH_SOURCE")"
EDIT: $BASH_SOURCE is, of course, a bash extension not available in other shells. If your script can't count on running in bash, use this instead:
case "$0" in
*/*)
cd "$(dirname "$0")" ;;
*)
me="$(which "$0")"
if [ -n "$me" ]; then
cd "$(dirname "$me")"
else
echo "Can't locate script directory" >&2
exit 1
fi ;;
esac
BTW, the construct [ ! -f file-3*.jar ] makes me nervous, since it'll fail bizarrely if there's ever more than one matching file. (I know, that's not supposed to happen; but things that aren't supposed to happen have any annoying tendency to happen anyway.) I'd use this instead:
matchfiles=(file-3*.jar)
if [ ! -f "${matchfiles[0]}" ]; then
...
Again, if you can't count on bash extensions, here's an alternative that should work in any POSIX shell:
if [ ! -f "$(echo file-3*.jar)" ]; then
Note that this will fail (i.e. act as though the file didn't exist) if there's more than one match.
I think the problem lies elsewhere, as the script works as expected on Mac OS X here:
$ if [ ! -f file-3*.jar ]; then echo "[INFO] jar could not be found."; fi
[INFO] jar could not be found.
$ touch file-302.jar
$ if [ ! -f file-3*.jar ]; then echo "[INFO] jar could not be found."; fi
$
Perhaps your script is being run under the wrong shell, or in the wrong working directory ?
It's not that it doesn't work for you, it doesn't work for your users? The default shell for OS X has changed over the years (see this post) - but it looks like your comment says you have the #! in place.
Are you sure that your users have the JAR file in the right place? Perhaps it's not the script being wrong as much as it's telling you the correct answer - the required file is missing from where the script is being run.
This isn't so much an answer, as a strategy: consider some serious logging. Echo messages such as "[INFO] jar could not be found." both to the screen and to a log file, then add extra logging, such as the values of $PWD, $SHELL and $0 to the log. Then, when your customers/co-workers try to run the script and fail, they can email the log to you.
I would probably use something like
screenlog() {
echo "$*"
echo "$*" >> $LOGFILE
}
log() {
echo "$*" >> $LOGFILE
}
Define $LOGFILE at the top of your script. Then pepper your script with statements like screenlog "[INFO] jar could not be found." or log "\$PWD: $PWD".

Quick bash script to run a script in a specified folder?

I am attempting to write a bash script that changes directory and then runs an existing script in the new working directory.
This is what I have so far:
#!/bin/bash
cd /path/to/a/folder
./scriptname
scriptname is an executable file that exists in /path/to/a/folder - and (needless to say), I do have permission to run that script.
However, when I run this mind numbingly simple script (above), I get the response:
scriptname: No such file or directory
What am I missing?! the commands work as expected when entered at the CLI, so I am at a loss to explain the error message. How do I fix this?
Looking at your script makes me think that the script you want to launch a script which is locate in the initial directory. Since you change you directory before executing it won't work.
I suggest the following modified script:
#!/bin/bash
SCRIPT_DIR=$PWD
cd /path/to/a/folder
$SCRIPT_DIR/scriptname
cd /path/to/a/folder
pwd
ls
./scriptname
which'll show you what it thinks it's doing.
I usually have something like this in my useful script directory:
#!/bin/bash
# Provide usage information if not arguments were supplied
if [[ "$#" -le 0 ]]; then
echo "Usage: $0 <executable> [<argument>...]" >&2
exit 1
fi
# Get the executable by removing the last slash and anything before it
X="${1##*/}"
# Get the directory by removing the executable name
D="${1%$X}"
# Check if the directory exists
if [[ -d "$D" ]]; then
# If it does, cd into it
cd "$D"
else
if [[ "$D" ]]; then
# Complain if a directory was specified, but does not exist
echo "Directory '$D' does not exist" >&2
exit 1
fi
fi
# Check if the executable is, well, executable
if [[ -x "$X" ]]; then
# Run the executable in its directory with the supplied arguments
exec ./"$X" "${#:2}"
else
# Complain if the executable is not a valid
echo "Executable '$X' does not exist in '$D'" >&2
exit 1
fi
Usage:
$ cdexec
Usage: /home/archon/bin/cdexec <executable> [<argument>...]
$ cdexec /bin/ls ls
ls
$ cdexec /bin/xxx/ls ls
Directory '/bin/xxx/' does not exist
$ cdexec /ls ls
Executable 'ls' does not exist in '/'
One source of such error messages under those conditions is a broken symlink.
However, you say the script works when run from the command line. I would also check to see whether the directory is a symlink that's doing something other than what you expect.
Does it work if you call it in your script with the full path instead of using cd?
#!/bin/bash
/path/to/a/folder/scriptname
What about when called that way from the command line?

Resources