I have a bash script, which, at one point asks the user for confirmation. I do this by reading a single character, which is then transformed to lower case and checked if it is 'y'. If not, the script exits.  Now, if I simply press enter on the input read, I get error: unary operator expected. How can I prevent this issue or catch the error?  Code snippet:  echo -ne "Confirm [y/n]: " read -n1 uc  if [ ${uc,,} != "y" ] then     exit 0 fi
1847
Or, an introductory guide to robust filename handling and other string passing in shell scripts.  I wrote a shell script which works well most of the time. But it chokes on some inputs (e.g. on some file names).  I encountered a problem such as the following:   I have a file name containing a space hello world, and it was treated as two separate files hello and world. I have an input line with two consecutive spaces and they shrank to one in the input. Leading and trailing whitespace disappears from input lines. Sometimes, when the input contains one of the characters \[*?, they are replaced by some text which is is actually the name of files. There is an apostrophe ' (or a double quote ") in the input and things got weird after that point. There is a backslash in the input (or: I am using Cygwin and some of my file names have Windows-style \ separators).   What is going on and how do I fix it?
24925
I am writing a menu based bash script, one of the menu options is to send an email with a text file attachment. I am having trouble with checking if my file is a text file. Here is what I have:  fileExists=10 until [ $fileExists -eq 9 ] do   echo "Please enter the name of the file you want to attach: "   read attachment   isFile=$(file $attachment | cut -d\ -f2)   if [[ $isFile = "ASCII" ]]     then       fileExists=0     else       echo "$attachment is not a text file, please use a different file"   fi done   I keep getting the error cut: delimiter must be a single character.
120370
I have been teaching myself bash scripting and have run into an issue. I have written a script to take input from the user, using the 'read' command, and make that input a variable to use later in the script. The script works, but....  I would like to be able to get it setup using 'dialog'. I found out that  'dialog --inputbox' will direct the output to 'stderr' and in order to get that input as a variable you have to direct it to a file and then retrieve it. The code I found to explain this is:  #!/bin/bash dialog --inputbox \  "What is your username?" 0 0 2&gt; /tmp/inputbox.tmp.$$  retval=$?  input=`cat /tmp/inputbox.tmp.$$`  rm -f /tmp/inputbox.tmp.$$  case $retval in 0)  echo "Your username is '$input'";; 1)  echo "Cancel pressed.";;  esac   I see that it is sending the sdterr to the /tmp/inputbox.tmp.$$ with 2>, but the output file looks like 'inputbox.tmp.21661'. When I try and cat the file it gives me an error. So I am still unable to get the user input from the --inputbox as a variable.   Example Script:   echo "  What app would you like to remove? "  read dead_app  sudo apt-get remove --purge $dead_app   So as you can see it is a basic script. Is it even possible to get the variable as a word from dialog --inputbox?
7248
If I try to run a;;b in sh, I get this error:  sh: &lt;number&gt;: Syntax error: ";;" unexpected   If I try a;;;b I get the same error, not ;;; instead of ;;, so I think that ;; means something, although I don't know what does it mean.  Here is an example:  $ echo A;;echo B sh: 1: Syntax error: ";;" unexpected $ echo A;;;echo B sh: 1: Syntax error: ";;" unexpected $ echo A; ;echo B sh: 1: Syntax error: ";" unexpected   Here you can see that when I use ; ; instead of ;; the error is different, pertaining to the fact that I used ; without a command before. ;; seems to be a different operator, although I don't know what it applies to.
48283
I am taking the Linux Essentials class and was doing well until I hit the scripting chapter. I simply do not understand these concepts.  Wondering if someone can break the following down into ultra simplistic terms or point me to a better reference to learn it. I'm currently using netacad's curriculum.        From the text book (with minor formatting changes):     There are some special variables in addition to the ones you set. You   can pass arguments to your script:  #!/bin/bash echo "Hello $1"       A dollar sign followed by a number N corresponds to the Nth argument   passed to the script. If you call the example above with ./test.sh the   output will be Hello Linux. The $0 variable contains the name of the   script itself.      After a program runs, be it a binary or a script, it returns an exit   code which is an integer between 0 and 255. You can test this through   the $? variable to see if the previous command completed successfully.     I understand how to assign variables and how they work with the $ but the whole issue with $0 and $1 -- I just don't get it.    Any help would be much appreciated.
25581
I'm reading shell tutorial today from   In which it mentions:     If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you whould preceed that using a backslash () as follows:   echo 'It\'s Shell Programming'   I tried this on my centos server, it doesn't work, a &gt; prompts out to hint me type more.  I was wondering, since two single quotes transform every special characters into normal characters,  which include escape symbol \, but exclude itself, the ', how should I represent a single single quote 'in a single-quoted phrase?
110271
I am having trouble with bash. I am trying to put a command in an if statement and then compare it to a string.  This works perfectly.  echo $(ipcs | grep Shared | awk '{print $2}')   When I put it in an if statement I get some problems.  $ if [ "$(ipcs | grep Shared | awk '{print $2}')" -eq "Shared"]; then   echo expression evaluated as true; else   echo expression evaluated as false; fi bash: [: missing `]' expression evaluated as false  $ if [ "$(ipcs | grep Shared | awk '{print $2}')" = "Shared"]; then   echo expression evaluated as true; else   echo expression evaluated as false; fi bash: [: missing `]' expression evaluated as false  $ if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared"]; then   echo expression evaluated as true; else   echo expression evaluated as false; fi bash: [: missing `]' expression evaluated as false   I tried ==, =, and -eq because I wasn't sure which one to use.
118424
I'm used to bash's builtin read function in while loops, e.g.:  echo "0 1       1 1       1 2       2 3" |\ while read A B; do     echo $A + $B | bc; done   I've been working on some make project, and it became prudent to split files and store intermediary results. As a consequence I often end up shredding single lines into variables. While the following example works pretty well,  head -n1 somefile | while read A B C D E FOO; do [... use vars here ...]; done   it's sort of stupid, because the while loop will never run more than once. But without the while,  head -n1 somefile | read A B C D E FOO; [... use vars here ...]   The read variables are always empty when I use them. I never noticed this behaviour of read, because usually I'd use while loops to process many similar lines. How can I use bash's read builtin without a while loop? Or is there another (or even better) way to read a single line into multiple (!) variables?  Conclusion  The answers teach us, it's a problem of scoping. The statement   cmd0; cmd1; cmd2 | cmd3; cmd4   is interpreted such that the commands cmd0, cmd1, and cmd4 are executed in the same scope, while the commands cmd2 and cmd3 are each given their own subshell, and consequently different scopes. The original shell is the parent of both subshells.
111834
I am trying to use a variable consisting of different strings separated with a | as a case statement test. For example:  string="\"foo\"|\"bar\"" read choice case $choice in     $string)         echo "You chose $choice";;     *)         echo "Bad choice!";; esac   I want to be able to type foo or bar and execute the first part of the case statement. However, both foo and bar take me to the second:  $ foo.sh foo Bad choice! $ foo.sh bar Bad choice!   Using "$string" instead of $string makes no difference. Neither does using string="foo|bar".   I know I can do it this way:  case $choice in     "foo"|"bar")         echo "You chose $choice";;     *)         echo "Bad choice!";; esac   I can think of various workarounds but I would like to know if it's possible to use a variable as a case condition in bash. Is it possible and, if so, how?
19072
In bash, from inside PROMPT_COMMAND, is there a way to tell if the user just hit 'return' and didn't enter a command?
77200
Any idea why echo statement is being executed in both scenarios?  Outputs it worked:  #!/bin/bash  rizwan='' if [ -n $rizwan ]; then   echo "it worked" fi   Replace -n with -z, and it outputs it worked when expecting no output:  #!/bin/bash  rizwan='' if [ -z $rizwan ]; then   echo "it worked" fi
57965
I am trying to create an spritz app. Everything was working fine, but since yesterday I keep getting this error:     ./spritz: line 176: syntax error: unexpected end of file   I have checked the script file and everything seems perfect. I am confused, I have an if statement at last and it looks correct! Here is the last portion:  #checks if speed is 150 157 if [[ $2 -eq 150 ]]; 158 then 159 starttime=$SECONDS 160      FS=$'\n' 161      for j in `grep --color=always -iP '\b[^aeiou\s]*[aeiou][^aeiou\s]*\K[aeiou]' $1`; 162      do 163            #Reads the text file in the centre of the screen 164            echo "                                                    ___________________" 165            echo "                                                             $j"; 166            echo "                                                    ___________________" 167            echo "                                                                               Speed 150 wpm" 168            sleep  0.9; 169            clear; 170       done 171 endtime=$(($SECONDS - $starttime)) 172            echo "You read $words_read words in $endtime seconds!" 173       exit 8 174 fi   What could cause that error?
62153
I understand test -n &lt;expression&gt; to return false if the expression evaluates to a string length of greater than 0.  Why then does the following happen?  Macbook:~ echo ${#undeclared_variable} 0 Macbook:~ test -n $undeclared_variable &amp;&amp; echo Foo Foo   Bash 4.x  My expectation is that since test -n $undeclared_variable should evaluate false, that Foo should not be echoed.  If I use [[  ]] instead of test, it works as expected.
99729
Here's my test bash script. I'm not able to get it to work. I'm seeing two errors:   Use of uninitialized value $answer in chop at /usr/sbin/adduser line 589. Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.   Here's my script:  #!/bin/bash sudo adduser myuser &lt;&lt; ENDX password password First Last     Y ENDX exit 0   Here is the output:  me@mycomputer$ ./adduser.sh  Adding user `myuser' ... Adding new group `myuser' (1001) ... Adding new user `myuser' (1001) with group `myuser' ... Creating home directory `/home/myuser' ... Copying files from `/etc/skel' ... Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Changing the user information for myuser Enter the new value, or press ENTER for the default         Full Name []:   Room Number []:         Work Phone []:  Home Phone []:  Other []: Use of uninitialized value $answer in chop at /usr/sbin/adduser line 589. Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590. Is the information correct? [Y/n] me@mycomputer$   This is on Kubuntu 12.04 LTS  $ bash --version bash --version GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)   Here are the lines from adduser (system script - unmodified by me) with notations of the two relevant line numbers:  for (;;) {        my $chfn = &amp;which('chfn');     &amp;systemcall($chfn, $new_name);     # Translators: [y/N] has to be replaced by values defined in your     # locale.  You can see by running "locale yesexpr" which regular     # expression will be checked to find positive answer.     print (gtx("Is the information correct? [Y/n] "));     chop (my $answer=&lt;STDIN&gt;);        &lt;-- LINE 589     last if ($answer !~ m/$noexpr/o); &lt;-- LINE 590 }
55899
I have written a small script to count number of occurrences of logs in a particular file. The following is my code:   #!/bin/sh count=1 while read line do     found=$( grep M $line )     OCCURENCE=$( grep M /log.txt)     if [ "$OCCURENCE" ]; then         echo $count")" $line &gt;&gt; filesave.txt     fi     count=$((count+1)) done &lt; log1.txt   but I am getting this error:  ./count.sh ./count.sh: syntax error at line 10: `found=$' unexpected
9236
How can I do something like this in bash?  if "`command` returns any error"; then     echo "Returned an error" else     echo "Proceed..." fi
56639
#!/bin/bash  SUBJECT="WARNING CPU USAGE HIGH" TO=gmail id MESSAGE=/tmp/messages echo "#######################" &gt; $MESSAGE echo "CPU statistics as follows.." &gt;&gt; $MESSAGE mpstat &gt;&gt; $MESSAGE echo "#######################" &gt;&gt; $MESSAGE CPU_USAGE=$(top -b -n1 | awk '/^Cpu/ {print $2}' | cut -d. -f1) [ $CPU_USAGE -gt 85 ] &amp;&amp; mail -s "$SUBJECT" "$TO" &lt; $MESSAGE`   ./cpu.sh: line 11: [: -gt: unary operator expected What might be the reason