I wrote a really simple file explorer using ls with a shell script. I used a while loop to make the script run forever (until Ctrl+C), but the while loop doesn't seem to work. I get this error
./fileexplorer: line 5: syntax error near unexpected token `done'
./fileexplorer: line 5: `done'`
My code is this:
#!/bin/bash
ls -l $1
while :
browse()
done
function browse()
{
read file;
if [ -f $file ]
if test -e $file
echo "Starting $file with nano."
echo "Press a key to open the file."
pause
nano $file
if test -d $file
ls -l $file
}
That's not the correct syntax, you need something like:
while CONDITION ; do
ACTION
done
Without the do, the done is indeed unexpected. In addition, your if statements should be of the form:
if CONDITION ; then
ACTION
fi
The bash man page shows the correct forms in more detail:
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
while list-1; do list-2; done
Keep in mind those shown above are my preferred form, with the do/then on the same line as the while/if. You can also leave off the ; and move the do/then on to the next line but I consider that unnecessarily wasteful of screen real estate.
Below script should work ..
#!/bin/bash
function browse()
{
read file;
if [ -f $file ]
then
if [ -e $file ]
then
echo "Starting $file with nano."
echo "Press a key to open the file."
sleep 2
nano $file
fi
fi
if [ -d $file ]
then
ls -l $file
fi
}
ls -l $1
while true;do
browse
done
Related
I have created a shell script in order to find 2 files. While it works with 1 it does not work with 2 or multiple. Any help?
#!/bin/bash
FILENAME="abc"
if [ -f "${FILENAME}"* ]
then
echo "EXISTS"
else
echo "NOT EXISTS"
fi
Expected: EXISTS
Error:
./test.sh: line 5: [: abc1.sh: binary operator expected
NOT EXISTS
Error is here:
if [ -f "${FILENAME}"* ]
-f option accepts a single file. If there are more files that start
with $FILENAME then * is expanded and more than one file is passed
to -f. It's also reported by shellcheck:
$ ~/.cabal/bin/shellcheck test.sh
In test.sh line 5:
if [ -f "${FILENAME}"* ]
^-- SC2144: -f doesn't work with globs. Use a for loop.
If you want to check if there is at least one file that starts with
$FILENAME without using external tools such as find you need use
for loop like that:
#!/bin/bash
FILENAME="abc"
for file in "${FILENAME}"*
do
if [ -f "$file" ]
then
echo File exists
exit 0
fi
done
echo File does not exist.
exit 1
The simple way is to check if there less then 2 files with same name abc*:
#!/bin/bash
FILENAME="abc"
COUNT_FILES=$(find . -maxdepth 1 -name "$FILENAME*" -type f | wc -l)
if [[ $COUNT_FILES -lt 2 ]]
then
echo "NOT EXISTS"
else
echo "EXISTS"
fi
if ls /path/to/your/files* 1> /dev/null 2>&1
then
echo "files do exist"
else
echo "files do not exist"
fi
This is what I was looking for. What I wanted was a function that looks for single OR multiple files, which the code above performed perfectly. Thanks for the previous answers, much help.
I want to run this command source .env (sourcing a .env file) and if the .env file had some errors while sourcing. I want to show a message before the error output "Hey you got errors in your .env" else if there's no error, I don't want to show anything.
Here's a code sample that needs editing:
#!/bin/zsh
env_auto_sourcing() {
if [[ -f .env ]]; then
OUTPUT="$(source .env &> /dev/null)"
echo "${OUTPUT}"
if [ -n "$OUTPUT" ]; then
echo "Hey you got errors in your .env"
echo "$OUTPUT"
fi
}
You could use bash -n (zsh has has a -n option as well) to syntax check your script before sourcing it:
env_auto_sourcing() {
if [[ -f .env ]]; then
if errs=$(bash -n .env 2>&1);
then source .env;
else
printf '%s\n' "Hey you got errors" "$errs";
fi
fi
}
Storing the syntax check errors in a file is a little cleaner than the subshell approach you have used in your code.
bash -n has a few pitfalls as seen here:
How do I check syntax in bash without running the script?
Why not just use the exit code from the command source ?
You don't have to use bash -n for this because ...
If let's say your .env file contains these 2 invalid lines:
dsadsd
sdss
If you run your current accepted code using the example above:
if errs=$(bash -n .env 2>&1);
the above condition will fail to stop the file from sourcing.
So, you can use source command return code to handle all of this:
#!/bin/bash
# This doesn't actually source it. It just test if source is working
errs=$(source ".env" 2>&1 >/dev/null)
# get the return code
retval=$?
#echo "${retval}"
if [ ${retval} = 0 ]; then
# Do another check for any syntax error
if [ -n "${errs}" ]; then
echo "The source file returns 0 but you got syntax errors: "
echo "Error details:"
printf "%s\n" "${errs}"
exit 1
else
# Success here. we know that this command works without error so we source it
echo "The source file returns 0 and no syntax errors: "
source ".env"
fi
else
echo "The source command returns an error code ${retval}: "
echo "Error details:"
printf "%s\n" "${errs}"
exit 1
fi
The best thing with this approach is, it will check both bash syntax and source syntax as well:
Now you can test this data in your env file:
-
~
#
~<
>
I have only one condition to check. And i would like to use the if-else construct in shell script. How do i write it. Most of the docs show that the construct is doing multiple aspects thats why they use
if []; then
echo "do something"
elif
echo "somethingelse"
else
echo "something 2"
fi
But in my case i am writing my construct like the below. It gives syntax issues.
#!/bin/sh
hadoopFileList=`hadoop fs -ls /app/SmartAnalytics/Apps/service_request_transformed.db/sr_denorm_bug_details/ | sed '1d;s/ */ /g' | cut -d\ -f8`
destination="/apps/phodisvc/creandoStaging"
scpData()
{
for file in $hadoopFileList
do
echo $file
echo "copying file to the staging directory"
hadoop fs -copyToLocal $file $destination
sleep 2s
echo "deleting the file"
echo ${file##*/}
done
}
if [[ -d "$destination" ]]; then
#file exists copy data
scpData()
else
#else create directory and copy data
mkdir -p $destination
scpData()
fi
You should not call your function with (), only definition needes them.
wrong:
myFunction() {
echo "This line is from my Function"
}
myFunction()
Right way:
myFunction() {
echo "This line is from my Function"
}
myFunction
As PS. mentioned, a bash function like scpData should be called without ().
Other than that, your if[];then ... else ... fi syntax is correct.
Thus your if-loop will work as:
if [ -d "$destination" ]; then
scpData
else
mkdir -p $destination
scpData
fi
In this particular case, however, the if-loop is not necessary,
because mkdir's -p option does check the condition.
i.e., it only makes directory if it doesn't exist.
So I re-wrote your if-loop (without using if-else-fi) as following:
mkdir -p $destination
scpData
which does the same thing!
I have been trying to make a shell script in bash that will display the following:
You are the super user (When I run the script as root).
You are the user: "user" (When I run the script as a user).
#!/bin/bash/
if { whoami | grep "root" }; then
echo $USER1
else
echo $USER2
fi
I keep recieving these syntax error messages:
script.sh: line 2: syntax error near unexpected token `then'
script.sh: line 2: `if { whoami | grep "root" }; then'
Could someone help me out?
If braces are used to chain commands then the last command must have a command separator after it.
{ foo ; bar ; }
userType="$(whoami)"
if [ "$userType" = "root" ]; then
echo "$USER1"
else
echo "$USER2"
fi
pay attention with your first line, the correct syntax for she-bang is:
#!/bin/bash
everything you put there, is the interpreter of your script, you can also put something like #!/usr/bin/python for python scripts, but your question is about the if statement, so you can do this in two ways in shell script using
if [ test ] ; then doSomething(); fi
or
if (( test )) ; then doSomething(); fi
so to answer your question basically you need to do this
#!/bin/bash
if [ `id -u` -eq 0 ] ; then
echo "you are root sir";
else
echo "you are a normal user"
fi
if (( "$USER" = "root" )); then
echo "you are root sir";
else
echo "you are a normal user"
fi
note that you could use a command using `cmd` or $(cmd) and compare using -eq (equal) or = (same), hope this help you :-)
How do I check if file exists in bash?
When I try to do it like this:
FILE1="${#:$OPTIND:1}"
if [ ! -e "$FILE1" ]
then
echo "requested file doesn't exist" >&2
exit 1
elif
<more code follows>
I always get following output:
requested file doesn't exist
The program is used like this:
script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE
Any ideas please?
I will be glad for any help.
P.S. I wish I could show the entire file without the risk of being fired from school for having a duplicate. If there is a private method of communication I will happily oblige.
My mistake. Fas forcing a binary file into a wrong place. Thanks for everyone's help.
Little trick to debugging problems like this. Add these lines to the top of your script:
export PS4="\$LINENO: "
set -xv
The set -xv will print out each line before it is executed, and then the line once the shell interpolates variables, etc. The $PS4 is the prompt used by set -xv. This will print the line number of the shell script as it executes. You'll be able to follow what is going on and where you may have problems.
Here's an example of a test script:
#! /bin/bash
export PS4="\$LINENO: "
set -xv
FILE1="${#:$OPTIND:1}" # Line 6
if [ ! -e "$FILE1" ] # Line 7
then
echo "requested file doesn't exist" >&2
exit 1
else
echo "Found File $FILE1" # Line 12
fi
And here's what I get when I run it:
$ ./test.sh .profile
FILE1="${#:$OPTIND:1}"
6: FILE1=.profile
if [ ! -e "$FILE1" ]
then
echo "requested file doesn't exist" >&2
exit 1
else
echo "Found File $FILE1"
fi
7: [ ! -e .profile ]
12: echo 'Found File .profile'
Found File .profile
Here, I can see that I set $FILE1 to .profile, and that my script understood that ${#:$OPTIND:1}. The best thing about this is that it works on all shells down to the original Bourne shell. That means if you aren't running Bash as you think you might be, you'll see where your script is failing, and maybe fix the issue.
I suspect you might not be running your script in Bash. Did you put #! /bin/bash on the top?
script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE
You may want to use getopts to parse your parameters:
#! /bin/bash
USAGE=" Usage:
script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE
"
while getopts gpr:d: option
do
case $option in
g) g_opt=1;;
p) p_opt=1;;
r) rfunction_id="$OPTARG";;
d) dfunction_id="$OPTARG";;
[?])
echo "Invalid Usage" 1>&2
echo "$USAGE" 1>&2
exit 2
;;
esac
done
if [[ -n $rfunction_id && -n $dfunction_id ]]
then
echo "Invalid Usage: You can't specify both -r and -d" 1>&2
echo "$USAGE" >2&
exit 2
fi
shift $(($OPTIND - 1))
[[ -n $g_opt ]] && echo "-g was set"
[[ -n $p_opt ]] && echo "-p was set"
[[ -n $rfunction_id ]] && echo "-r was set to $rfunction_id"
[[ -n $dfunction_id ]] && echo "-d was set to $dfunction_id"
[[ -n $1 ]] && echo "File is $1"
To (recap) and add to #DavidW.'s excellent answer:
Check the shebang line (first line) of your script to ensure that it's executed by bash: is it #!/bin/bash or #!/usr/bin/env bash?
Inspect your script file for hidden control characters (such as \r) that can result in unexpected behavior; run cat -v scriptFile | fgrep ^ - it should produce NO output; if the file does contain \r chars., they would show as ^M.
To remove the \r instances (more accurately, to convert Windows-style \r\n newline sequences to Unix \n-only sequences), you can use dos2unix file to convert in place; if you don't have this utility, you can use sed 's/'$'\r''$//' file > outfile (CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file); to remove all \r instances (even if not followed by \n), use tr -d '\r' < file > outfile (CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file).
In addition to #DavidW.'s great debugging technique, you can add the following to visually inspect all arguments passed to your script:
i=0; for a; do echo "\$$((i+=1))=[$a]"; done
(The purpose of enclosing the value in [...] (for example), is to see the exact boundaries of the values.)
This will yield something like:
$1=[-g]
$2=[input.txt]
...
Note, though, that nothing at all is printed if no arguments were passed.
Try to print FILE1 to see if it has the value you want, if it is not the problem, here is a simple script (site below):
#!/bin/bash
file="${#:$OPTIND:1}"
if [ -f "$file" ]
then
echo "$file found."
else
echo "$file not found."
fi
http://www.cyberciti.biz/faq/unix-linux-test-existence-of-file-in-bash/
Instead of plucking an item out of "$#" in a tricky way, why don't you shift off the args you've processed with getopts:
while getopts ...
done
shift $(( OPTIND - 1 ))
FILE1=$1