If: Expression syntax - Error with a C Shell Script - unix

I'm working on debugging a C-shell script that was given to me to add options to. This script, clean, is supposed to display the name of each file in a given directory and allows the user to decide whether or not keep or delete them. The problem is, when executed with a directory as an argument (or without) the error "If: Expression Syntax." Here's what it looks like. (now, as of 11/11)
## script name: clean
## helps to remove unwanted files from a directory
#!/bin/csh -vx
if ($#argv !=1) then
echo usage: $0 directory; exit(1)
else if (! -d $1) then
echo $1 not a directory; exit(1)
endif
set dir = $1
chdir $dir
set files = *
# process files
foreach file ($files)
if (! -f $file) continue
echo ' ' ## gives a blank line
echo "file = $file" ## identifies file being processed
echo ' '
head $file
while (1)
echo -n rm $file '?? (y, n, \!, or q)' :
set c = $<
switch ($c)
case y:
if ( {rm $file} ) then
echo '*****' $file rm-ed
else
echo cannot rm $file
endif
break ## break out of while
case n:
echo '*****' $file not rm-ed
break
case q:
exit(0)
case \!:
echo command:
eval $<
## in $< the variable $file can be used
endsw
end ## of while
end ## of foreach

Related

How To Check For Directory On A Give Argument

If the argument is 0 then script should check directory called “App0” is in the windows path variable. If not exists, then add \App0 in the path. I Am Struggling To Understand ( If the argument is 0 ).
My Work So Far.
if [ -d "${Appo}" ]; then
echo "Appo Doesn't Exist."
mkdir Appo
echo "File Created"
fi
Thank You
#!/bin/sh
if [[ $# == 0 ]]
then
echo "zero args"
fi
for arg in "$#" # You might get more than one argument.
do
dir="App${arg}" # Make the name by combining the strings.
if [[ -d $dir ]]
then
echo "App$arg exists"
else
mkdir "$dir" # Be careful the name supplied may contain spaces.
echo "Created directory: $dir"
fi
done

How to tell script to look only into a specific folder

I'm trying to make a recycle bin for UNIX, so I have two scripts. 1 to delete the file and move it to the bin, the other script to restore the file back to its original location.
my restore script only works if the person gives the path to the deleted file.
ex: sh restore ~/trashbin/filename
How do I hardcode into my script so that I don't need to give the path to the deleted file it should already know to look in the trashbin for the file. My restore script works only when someone calls in the path to the file.
#!/bin/bash
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
function restoreFile() {
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
rorgpath=$(grep "$rname" ~/.restore.info | cut -d":" -f2)
rdirect=$(dirname "$rorgpath")
#echo $orgpath
if [ ! -d "$rdirect" ]
then
mkdir -p $rdirect
#echo $var
mv $rlink $rorgpath
else
mv $rlink $rorgpath
fi
}
if [ -z "$1" ]
then
echo "Error no filename provided."
exit 1
elif [ ! -f "$1" ]
then
echo "Error file does not exist."
exit 1
elif [ -f "$rorgpath" ]
then
echo "File already exists in original path."
read -p "Would you like to overwrite it? (y/n)" ovr
if [[ $ovr = y || $ovr = Y || $ovr = yes ]]
then
echo "Restoring File and overwriting."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
else
echo "Restoring file into original path."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
When you "remove" the file from the file-system to your trash-bin, move it so that its path is remembered. Example: removing file /home/user/file.txt should mean moving this file to ~/.trash/home/user/file.txt. That way, you'll be able to restore files to the original location, and you'll have auto-complete work, since you can do: sh restore ~/.trash/<TAB><TAB>

Unix determine if a file is empty

I am attempting to make a script that will check to see if there is any tyext within a file. I have developed the following script. I have made it check to see if there is exactly 2 arguments, see if the file exists, but I am having trouble checking the file for text within it. The code is as follows:
#!/bin/ksh
#check if number of arguments are 2
if [ $# -ne 2 ]; then
echo "Does not equal two arguments"
echo "Usage $0 inputfile outputfile"
exit 1
fi
#check if input file exists
if [ ! -f $1 ]; then
echo "$1 not found!"
exit 1
fi
#Check if input file is null
#This next block of code is where the issue is
if [ grep -q $1 -eq 0 ]; then
echo "$1 must have text within the file"
exit 1
fi
Any help would be appreciated
test's "-s" option checks if the file is empty -- see manual. So your last chunk would become
#Check if input file is null
#This next block of code is where the issue is
if [ ! -s $1 ]; then
echo "$1 must have text within the file"
exit 1
fi
Try using stat
stat -c %s filename

Unix run a script with -help option

I have the below script that is expected to work when the user invokes sh <scriptName> <propertyfile> It does work when I provide this at the dollar prompt. However, I am having two issues with the script.
If I provide just one argument, ie if I do - sh <scriptName>, I see the below error -
my-llt-utvsg$ sh temp.sh
Usage temp.sh
When I do -help, I see the below error -
my-llt-utvsg$ sh tmp.sh -help
-help does not exist
What am I doing wrong? Can someone please advise? I am a software developer that very rarely needs to do shell scripting, so please go easy on me ;)
#!/bin/bash
FILE="system.properties"
FILE=$1
if [ ! -f $FILE ];
then
echo "$FILE does not exist"
exit
fi
usage ()
{
echo "Usage $0 $FILE"
exit
}
if [ "$#" -ne 1 ]
then
usage
fi
if [ "$1" = "-help" ] ; then
echo ""
echo '############ HELP PROPERTIES ############ '
echo ""
echo 'Blah.'
exit
The reason your
if [ "$1" = "-help" ] ; then
check is not working is that it only checks $1 or the first argument.
Try instead:
for var in "$#"
do
if [ "$var" = "-help" ] ; then
echo ""
echo '############ HELP PROPERTIES ############ '
echo ""
echo 'Blah.'
fi
done
Which will loop over each argument and so will run if any of them are -help.
Try this as well:
#!/bin/bash
FILES=()
function show_help_info_and_exit {
echo ""
echo '############ HELP PROPERTIES ############ '
echo ""
echo 'Blah.'
exit
}
function show_usage_and_exit {
echo "Usage: $0 file"
exit
}
for __; do
if [[ $__ == -help ]]; then
show_help_info_and_exit
elif [[ -f $__ ]]; then
FILES+=("$__")
else
echo "Invalid argument or file does not exist: $__"
show_usage_and_exit
fi
done
if [[ ${#FILES[#]} -ne 1 ]]; then
echo "Invalid number of file arguments."
show_usage_and_exit
fi
echo "$FILES"

Find out if a command exists on POSIX system

I want to be able to tell if a command exists on any POSIX system from a shell script.
On Linux, I can do the following:
if which <command>; then
...snip...
fi
However, Solaris and MacOS which do not give an exit failure code when the command does not exist, they just print an error message to STDOUT.
Also, I recently discovered that the which command itself is not POSIX (see http://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html)
Any ideas?
command -v is a POSIX specified command that does what which does.
It is defined to to return >0 when the command is not found or an error occurs.
You could read the stdout/stderr of "which" into a variable or an array (using backticks) rather than checking for an exit code.
If the system does not have a "which" or "where" command, you could also grab the contents of the $PATH variable, then loop over all the directories and search for the given executable. That's essentially what which does (although it might use some caching/optimization of $PATH results).
One which utility is available as shell script in the Git repository of debianutils package of Debian Linux. The script seems to be POSIX compatible and you could use it, if you take into account copyright and license. Note that there have been some controversy whether or not and how the which utility should be deprecated; (at time of writing) current version in Git shows deprecation message whereas an earlier version added later removed -s option to enable silent operation.
command -v as such is problematic as it may output a shell function name, an alias definition, a keyword, a builtin or a non-executable file path. On the other hand some path(s) output by which would not be executed by shell if you run the respective argument as such or as an argument for command. As an alternative for using the which script, a POSIX shell function using command -v could be something like
#!/bin/sh
# Argument $1 should be the basename of the command to be searched for.
# Outputs the absolute path of the command with that name found first in
# a directory listed in PATH environment variable, if the name is not
# shadowed by a special built-in utility, a regular built-in utility not
# associated with a PATH search, or a shell reserved word; otherwise
# outputs nothing and returns 1. If this function prints something for
# an argument, it is the path of the same executable as what 'command'
# would execute for the same argument.
executable() {
if cmd=$(unset -f -- "$1"; command -v -- "$1") \
&& [ -z "${cmd##/*}" ] && [ -x "$cmd" ]; then
printf '%s\n' "$cmd"
else
return 1
fi
}
Disclaimer: Note that the script using command -v above does not find an executable whose name equals a name of a special built-in utility, a regular built-in utility not associated with a PATH search, or a shell reserved word. It might not find an executable either in case if there is non-executable file and executable file available in PATH search.
A function_command_exists for checking if a command exists:
#!/bin/sh
set -eu
function_command_exists() {
local command="$1"
local IFS=":" # paths are delimited with a colon in $PATH
# iterate over dir paths having executables
for search_dir in $PATH
do
# seek only in dir (excluding subdirs) for a file with an exact (case sensitive) name
found_path="$(find "$search_dir" -maxdepth 1 -name "$command" -type f 2>/dev/null)"
# (positive) if a path to a command was found and it was executable
test -n "$found_path" && \
test -x "$found_path" && \
return 0
done
# (negative) if a path to an executable of a command was not found
return 1
}
# example usage
echo "example 1";
command="ls"
if function_command_exists "$command"; then
echo "Command: "\'$command\'" exists"
else
echo "Command: "\'$command\'" does not exist"
fi
command="notpresent"
if function_command_exists "$command"; then
echo "Command: "\'$command\'" exists"
else
echo "Command: "\'$command\'" does not exist"
fi
echo "example 2";
command="ls"
function_command_exists "$command" && echo "Command: "\'$command\'" exists"
command="notpresent"
function_command_exists "$command" && echo "Command: "\'$command\'" does not exist"
echo "End of the script"
output:
example 1
Command: 'ls' exists
Command: 'notpresent' does not exist
example 2
Command: 'ls' exists
End of the script
Note that even the set -eu that turns -e option for the script was used the script was executed to the last line "End of the script"
There is no Command: 'notpresent' does not exist in the example 2 because of the && operator so the execution of echo "Command: "\'$command\'" does not exist" is skipped but the execution of the script continues till the end.
Note that the function_command_exists does not check if you have a right to execute the command. This needs to be done separately.
Solution with command -v <command-to-check>
#!/bin/sh
set -eu;
# check if a command exists (Yes)
command -v echo > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 1>"
fi
# check if a command exists (No)
command -v command-that-does-not-exists > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 2>"
fi
produces:
<handle not found 2>
because echo was found at the first example.
Solution with running a command and handling errors including command not found.
#!/bin/sh
set -eu;
# check if a command exists (No)
command -v command-that-does-not-exist > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 2>"
fi
# run command and handle errors (no problem expected, echo exist)
echo "three" && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 3>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 3>"
fi
# run command and handle errors (<handle not found 4> expected)
command-that-does-not-exist && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 4>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 4>"
fi
# run command and handle errors (command exists but <handle other error 5> expected)
ls non-existing-path && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 5>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 5>"
fi
produces:
<handle not found 2>
three
./function_command_exists.sh: 34: ./function_command_exists.sh: command-that-does-not-exist: not found
<handle not found 4>
ls: cannot access 'non-existing-path': No such file or directory
<handle other error 5>
The following works in both bash and zsh and avoids both functions and aliases.
It returns 1 if the binary is not found.
bin_path () {
if [[ -n ${ZSH_VERSION:-} ]]; then
builtin whence -cp "$1" 2> /dev/null
else
builtin type -P "$1"
fi
}

Resources