Difference between pages "Error messages and their solutions" and "BaBE - Bash By Examples"

From Linuxintro
(Difference between pages)
imported>ThorstenStaerk
 
imported>ThorstenStaerk
 
Line 1: Line 1:
This is a collection of known error messages and their solution. Mostly these error messages result from missing [[dependencies]].
+
<metadesc>BaBE - Bash by Examples; Your significant Linux scripting tutorial: Redirection, Piping, conditional execution, user dialogs, loops, process management, backticks, string replacement, pitfalls and much more.</metadesc>
  
=== a52 ===
+
BaBE - Bash By Examples; Your significant Linux scripting tutorial;;
'''Symptom''', in this case from [[build]]ing [[vlc]]:
 
[[configure]]: error: Could not find liba52 on your system: you may get it from http://liba52.sf.net/. Alternatively you can use --disable-a52 to disable the a52 plugin.
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i liba52-devel
 
  
=== atk ===
+
<pic src="http://www.linuxintro.org/images/Bash-scripting-mindmap.jpg" width=70% align=right caption=MindMap />
'''Symptom''', in this case from gqcam:
 
/usr/include/gtk/gtkwidget.h:40:21: fatal error: atk/atk.h: No such file or directory
 
compilation terminated.
 
make: *** [gqcam.o] Error 1
 
'''Solution''', in this case for SUSE Linux 11.3:
 
[[cp]] -r /usr/include/atk-1.0/atk/ /usr/include/
 
  
=== C compiler ===
+
= Hello world =
<pre>
+
The easiest way to get your feet wet with a programming language is to start with a program that simply outputs a trivial text, the so-called hello-world-example. Here it is for bash:
~/freeciv-2.1.9 # ./configure
+
* create a file named hello in your home directory with the following content:
checking build system type... i686-pc-linux-gnu
+
[http://en.wikipedia.org/wiki/Shebang_%28Unix%29 #!/bin/bash]
checking host system type... i686-pc-linux-gnu
+
[[echo]] "Hello, world!"
checking for a BSD-compatible install... /usr/bin/install -c
+
* [[open a console]], enter
checking whether build environment is sane... yes
+
cd
checking for gawk... gawk
+
chmod +x hello
checking whether make sets $(MAKE)... no
+
* now you can execute your file like this:
checking whether to enable maintainer-specific portions of Makefiles... no
+
# ./hello
checking for style of include used by make... none
+
Hello, world!
checking for gcc... no
+
* or like this:
checking for cc... no
+
# bash hello
checking for cc... no
+
Hello, world!
checking for cl... no
+
You see - the output of your shell [[program]] is the same as if you had entered the commands into a console.
configure: error: no acceptable C compiler found in $PATH
 
See `config.log' for more details.
 
linux-zcx2:~/freeciv-2.1.9 # gcc
 
If 'gcc' is not a typo you can use command-not-found to lookup the package that contains it, like this:
 
    cnf gcc
 
linux-zcx2:~/freeciv-2.1.9 # yast -i gcc-c++
 
</pre>
 
  
=== C++ compiler ===
+
= calling commands =
Problem e.g.:
+
In your shell script you can call every command that you can call when [[opening a console]]:
  CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.  Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
+
<source>
'''Solution''', e.g. under Debian:
+
  echo "This is a directory listing, latest modified files at the bottom:"
  aptitude install build-essential
+
ls -ltr
 +
echo "Now calling a browser"
 +
firefox
 +
  echo "Continuing with the script"
 +
</source>
  
=== C header files ===
+
= variables =
'''Symptom:''' When starting [[vmware]] player you get an error message:
+
== input ==
  C header files matching your running kernel were not found. Refer to your distribution's documentation for installation instructions.
+
To show you how to deal with variables, we will now write a script that asks for your name and greets you:
'''Solution''', in this case for SUSE Linux 12.1:
+
  echo "what is your name? "
[[yast]] -i kernel-source
+
read name
 +
  echo "hello $name"
 +
You see that the name is stored in a variable $name. Note the quotation marks '''"''' around "hello $name". By using these you say that you want variables to be replaced by their content. If you were to use apostrophes, the name would not be printed, but $name instead.
  
=== capabilities.h ===
+
== ${} ==
'''Symptom''', in this case from [[build]]ing vdr
+
The ${} operator stands for the variable, there is no difference if you write
  vdr.c:35:28: fatal error: sys/capability.h: No such file or directory
+
  echo "$name"
'''Solution''', in this case for SUSE 11.3
+
or
  [[yast]] -i libcap-devel
+
echo "${name}"
 +
So what is the sense of this? Imagine you want to echo a string directly, without any blank, after the content of a variable:
 +
<source>
 +
  echo "if I add the syllable owa to your name it will be ${name}owa"
 +
</source>
  
=== cairo ===
+
== common mistakes ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
Note that the variable is called $name, however the correct statement to read it from the keyboard is
  /usr/include/gdk/gdkscreen.h:31:19: fatal error: cairo.h: No such file or directory
+
  read name
'''Solution''', in this case for SUSE 11.3:
+
It is a common mistake to write
  [[cp]] /usr/include/cairo/* /usr/include/
+
  read $name
 +
which means "read a string and store it into the variable whose name is stored in $name"
  
=== DBUS ===
+
= parameters =
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
<source>
configure: error: Couldn't find DBus >= 1.0.0, install libdbus-dev ?
+
echo "Here are all parameters you called this script with: $@"
'''Solution''', in this case for SUSE 11.3:
+
echo "Here is parameter 1: $1"
[[yast]] -i dbus-1-devel
+
echo "Which parameter do you want to be shown? "
 +
read number
 +
args=("$@")
 +
echo "${args[$number-1]}"
 +
</source>
  
=== firefox ===
+
= return codes =
'''Symptom:''' When trying to start [[firefox]] you get a message:
+
Every bash script can communicate with the rest of the system by
Firefox is already running, but is not responding. To open a new window, you must first close the existing Firefox process, or restart your system.
+
* sending data to [[stdout]]
 +
* sending data to [[stderr]]
 +
* delivering a return code
 +
The return code is 0 if everything worked well. You can query it for the most recent command using $?:
 +
<source>
 +
bootstick@bootstick:~$ echo "hello world"; echo $?
 +
hello world
 +
0
 +
bootstick@bootstick:~$ echo "hello world">/proc/cmdline; echo $?
 +
bash: /proc/cmdline: Permission denied
 +
1
 +
</source>
  
'''Solution''', in this case for SUSE Linux 12.1:
+
In bash, true is 0 and false is any value but 0. There exist two commands, true and false that deliver true or false, respectively:
[[open a console]] and enter the [[command]]
+
bootstick@bootstick:~$ true; echo $?
  killall firefox-bin
+
0
 +
bootstick@bootstick:~$ false; echo $?
 +
  1
  
=== fribidi ===
+
= line feeds =
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
Let's look at the following script:
  [[configure]]: error: Package requirements (fribidi) were not met:  
+
  read name
   
+
if [ $name = "Thorsten" ]; then echo "I know you"; fi
  No package 'fribidi' found
+
Instead of a semicolon you can write a line feed like this:
   
+
  read name
Consider adjusting the PKG_CONFIG_PATH environment variable if you
+
  if [ $name = "Thorsten" ]
installed software in a non-standard prefix.
+
  then echo "I know you"
   
+
  fi
Alternatively, you may set the environment variables FRIBIDI_CFLAGS
+
And instead of a line feed you can use a semicolon:
and FRIBIDI_LIBS to avoid the need to call pkg-config.
+
  read name; if [ $name = "Thorsten" ]; then echo "I know you"; fi
  See the pkg-config man page for more details.
+
If you want to insert a line feed where you do not need one, e.g. to make the code better readable, you must prepend it with a backslash:
'''Solution''', in this case for SUSE 11.3:
+
  read \
  [[yast]] -i fribidi-devel
+
  name
 +
  if [ $name = "Thorsten" ]
 +
  then \
 +
    echo "I know you"
 +
fi
  
=== gcrypt ===
+
= storing a command's output =
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
To read a command's output into a variable use $(), backticks or [[piping]].
configure: error: libgcrypt version 1.1.94 or higher not found. Install libgcrypt or use --disable-libgcrypt. Have a nice day.
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i libgcrypt-devel
 
  
=== gdk ===
+
== $() ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
  arch=$(uname -m)
  /usr/include/gtk/gtk.h:32:21: fatal error: gdk/gdk.h: No such file or directory
+
  echo "Your system is a $arch system."
'''Solution''', in this case for SUSE Linux 11.3:
 
  [[cp]] -pr /usr/include/gtk-2.0/gdk /usr/include/
 
  
=== gdkconfig ===
+
== backticks ==
'''Symptom''':
+
  arch=`uname -m`
  /usr/include/gdk/gdktypes.h:55:23: fatal error: gdkconfig.h: No such file or directory
+
  echo "Your system is a $arch system."
compilation terminated.
 
[[make]]: *** [gqcam.o] Error 1
 
'''Solution''':
 
linux-noqb:~/gqcam-0.8 # cd /usr/include/
 
  linux-noqb:/usr/include # find -iname "gdkconfig*"
 
linux-noqb:/usr/include # cd /usr/lib64/
 
linux-noqb:/usr/lib64 # find -iname "gdkconfig*"
 
./gtk-2.0/include/gdkconfig.h
 
linux-noqb:/usr/lib64 # cp /usr/lib64/gtk-2.0/include/gdkconfig.h /usr/include/
 
  
=== gdk-pixbuf ===
+
== piping ==
'''Symptom''':
+
[[Piping]] is a very elegant concept in the Linux world. It allows you to take one command's output and use it as input for the next command. Now you can divide tasks into smaller tasks. For example instead of having a program counting all files in a directory you use one program (ls) to ''list'' all files in a directory and one program (wc) to count the lines:
/usr/include/gdk/gdkpixbuf.h:37:35: fatal error: gdk-pixbuf/gdk-pixbuf.h: No such file or directory
+
<source>
compilation terminated.
+
ls | wc -l
[[make]]: *** [gqcam.o] Error 1
+
</source>
'''Solution''':
+
You can also put the output into a variable, in this case $arch:
<pre>
+
<source>
linux-noqb:~/gqcam-0.8 # cd /usr/include/
+
uname -m | while read arch; do echo "Your system is a $arch system."; done
linux-noqb:/usr/include # find -iname "gdk-pixbuf*"
+
</source>
./gtk-2.0/gdk-pixbuf
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-enum-types.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-animation.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-features.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-core.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-transform.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-io.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-marshal.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-loader.h
 
./gtk-2.0/gdk-pixbuf/gdk-pixbuf-simple-anim.h
 
./gtk-2.0/gdk-pixbuf-xlib
 
./gtk-2.0/gdk-pixbuf-xlib/gdk-pixbuf-xlib.h
 
./gtk-2.0/gdk-pixbuf-xlib/gdk-pixbuf-xlibrgb.h
 
linux-noqb:/usr/include # cp -r /usr/include/gtk-2.0/gdk-pixbuf /usr/include/
 
</pre>
 
  
=== gettext ===
+
== comparison ==
'''Symptom''', in this example from [[build]]ing [[pidgin]]:
+
The advantage of using backticks over $() is that backticks also work in the sh shell. The advantage of using $() over backticks is that you can cascade them. In the example below we use this possibility to get a list of all files installed with rpm on the system:
  [[configure]]: error: GNU gettext tools not found; required for intltool
+
  filelist=$([[rpm]] -ql $(rpm -qa))
'''Solution''', in this case for SLES 11:
+
You can use the piping approach if you need to cascade in sh, but this is not focus of this bash tutorial.
# [[yast]] -i gettext-tools
 
  
=== gio ===
+
== common mistakes ==
'''Symptom''', in this case [[build]]ing from gqcam:
+
Usually unexperienced programmers try something like
/usr/include/gdk/gdkapplaunchcontext.h:30:21: fatal error: gio/gio.h: No such file or directory
+
uname -m | read arch
'''Solution''', in this case for SUSE Linux 11.3:
+
which [http://mywiki.wooledge.org/BashFAQ/024 does not work]. You must embed the read into a while loop.
[[cp]] -r /usr/include/glib-2.0/gio/ /usr/include/
 
  
=== glib ===
+
= conditions =
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
The easiest form of a condition in bash is this '''if''' example:
  error: glib.h: No such file or directory
+
  echo "what is your name? "
'''Solution''' (in this case for SUSE 11.3):
+
read name
  [[yast]] -i glib2-devel
+
  if [ $name = "Thorsten" ]; then echo "I know you"; fi
[[cp]] /usr/include/glib-2.0/glib.h /usr/include/
+
Now let's look closer at this, why does it work? Why is there a blank needed behind the [ sign? The answer is that [ is just an ordinary [[command]] in the shell. It delivers a return code for the expression that follows till the ] sign. To prove this we can write a script:
  cp -pr /usr/include/glib-2.0/glib /usr/include/
+
<source>
 +
if true; then echo "the command following if true is being executed"; fi
 +
  if false; then echo "this will not be shown"; fi
 +
</source>
  
=== glibconfig ===
+
== empty strings ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
An empty string evaluates to false inside the [ ] operators so it is possible to check if a string ''result'' is empty like this:
  /usr/include/glib/gtypes.h:34:24: fatal error: glibconfig.h: No such file or directory
+
# result=
'''Solution''', in this case for SUSE 11.3:
+
# if [ $result ]; then echo success; fi
  [[cp]] /usr/lib64/glib-2.0/include/glibconfig.h /usr/include/
+
  # result=good
 +
  # if [ $result ]; then echo success; fi
 +
success
  
=== gmodule ===
+
== arithmetic expressions ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
You can compare integer numbers like this:
  /usr/include/gio/giomodule.h:31:21: fatal error: gmodule.h: No such file or directory
+
  echo "what is your age? "
'''Solution''', in this case for SUSE 11.3:
+
read age
  [[cp]] /usr/include/glib-2.0/gmodule.h /usr/include/
+
if (( $age >= 21 )); then echo "Let's talk about sex."; fi
 +
However bash does not understand floating point numbers. To compare floating numbers you will use external programs such as bc:
 +
<source>
 +
  $ if [ $(echo "2.1<2.2"|bc) = 1 ]; then echo "correct"; else echo "wrong"; fi
 +
correct
 +
$ if [ $(echo "2.1>2.2"|bc) = 1 ]; then echo "correct"; else echo "wrong"; fi
 +
wrong
 +
</source>
  
=== gtk ===
+
== not equal ==
'''Symptom''', in this case from [[build]]ing [[kino]]:
+
To check if a variable is NOT equal to whatever, use !=:
checking for GTK2... configure: error: Package requirements (gthread-2.0 libglade-2.0 >= 2.5.0 gtk+-2.0 >= 2.6) were not met:
+
<source>
+
  if [ "$LANG" != "C" ]; then echo "please set your system lanugage to C"; fi
No package 'libglade-2.0' found
+
</source>
'''Solution''', in this case for SUSE 11.3:
 
  [[yast]] -i libglade2-devel
 
  
=== gtk-config ===
+
== common mistakes ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
Common mistakes are:
/bin/sh: gtk-config: command not found
+
* to forget the blank behind/before the [ or ] character
gqcam.c:32:21: fatal error: gtk/gtk.h: No such file or directory
+
* to forget the blank behind/before the equal sign
'''Solution''', in this case for SUSE 11.3:
+
* see [[what does "unary operator expected" mean]]
* install gtk 2.20
 
* copy the header files
 
[[cp]] -pr /usr/include/gtk-2.0/gtk/ /usr/include
 
  
=== gtk-window-dialog ===
+
= Redirections =
<pre>
+
To redirect the output of a [[command]] to a file you have to consider that there are two output streams in UNIX, [[stdout,stderr and stdin|stdout and stderr]].
frontend.c:411:44: error: ‘GTK_WINDOW_DIALOG’ undeclared (first use in this function)
 
frontend.c:411:44: note: each undeclared identifier is reported only once for each function it appears in
 
make: *** [frontend.o] Error 1
 
linux-noqb:~/gqcam-0.8 # cd
 
[1]+  Exit 16                yast2 sw_single  (wd: ~/gqcam-0.8)
 
(wd now: ~)
 
linux-noqb:~ # cd gtk+-2.20.1/
 
linux-noqb:~/gtk+-2.20.1 # grep -ri "gtk_window_dialog" *
 
ChangeLog.pre-1-0:      GTK_WINDOW_DIALOG as a destination for reparenting the child of
 
ChangeLog.pre-2-0:      * gtk/testgtk.c (dnd_drop): remove use of GTK_WINDOW_DIALOG
 
ChangeLog.pre-2-0:      * gtk/gtkcompat.h (GTK_WINDOW_DIALOG): compat #define
 
ChangeLog.pre-2-0:      GTK_WINDOW_DIALOG GTK_WINDOW_TOPLEVEL
 
ChangeLog.pre-2-0:      * gtk/gtkenums.h (enum GtkWindowType): remove GTK_WINDOW_DIALOG
 
</pre>
 
  
=== intltool ===
+
= filling files =
'''Symptom''', in this case from [[build]]ing [[pidgin]]:
+
To create a file, probably the easiest way is to use [[cat]]. The following example writes text into README till a line occurs that only contains the string "EOF":
  [[configure]]: error: The intltool scripts were not found. Please install intltool.
+
  cat >README<<EOF
'''Solution''', in this case with SLES 11:
+
  This is line 1
  # [[wget]] http://ftp.gnome.org/pub/gnome/sources/intltool/0.35/intltool-0.35.5.tar.bz2
+
  This is line 2
  # bunzip2 intltool-0.35.5.tar.bz2
+
  This is the last line
  # [[tar]] xvf intltool-0.35.5.tar
+
  EOF
  # [[cd]] intltool-0.35.5/
+
Afterwards, README will contain the 3 lines below the cat command and above the line with EOF.
# ./[[configure]] && [[make]] -j8 && make [[install]]
 
  
=== jpeg ===
+
= loops =
'''Symptom''', in this case from [[xawtv]]:
 
Oops:  jpeg library not found.  You need this one, please install.
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i libjpeg-devel
 
  
=== KDE ===
+
== for loops ==
'''Symptom''':
+
Here is an example for a for-loop. It makes a [[backup]] of all text files:
  ERROR: Could not find KDE4 kde4-config
+
for i in *.txt; do [[cp]] $i $i.bak; done
'''Solution''', e.g. under Debian:
+
The above command takes each .txt file in the current directory, stores it in the [[variable]] $i and copies it to $i.bak. So ''file''.txt gets copied to ''file''.txt.bat.
apt-get [[install]] kdelibs5-dev
 
  
=== liblavdisplay ===
+
You can also use subsequent numbers as a for loop using the command seq like this:
'''Symptom''', e.g. when compiling mjpegtools:
+
  for i in $([[seq]] 1 1 3); do [[echo]] $i; done
./.libs/liblavplay.so: undefined reference to `XOpenDisplay'
 
'''Solution''', e.g. under SUSE:
 
  [[yast]] -i libSDL-devel
 
  
=== libQtDBus ===
+
== while loops ==
'''Symptom''', in this case from running [[skype]]:
+
  $ while true; do read line; done
  skype: error while loading shared libraries: libQtDBus.so.4: cannot open shared object file: No such file or directory
 
'''Reason''': You do not have the 32bit libraries for Qt.
 
  
'''Solution''', in this case for SUSE 11.3:
+
= negations =
  [[yast]] -i libqt4-32bit
+
You can negate a result with the ! operator. $? is the last command's return code:
 +
# true
 +
# echo $?
 +
0
 +
# false
 +
# echo $?
 +
1
 +
# ! true
 +
# echo $?
 +
1
 +
# ! false
 +
# echo $?
 +
0
 +
So you get an endless loop out of:
 +
  while ! false; do echo hallo; done
  
=== libfontconfig ===
+
The following code checks the file /tmp/success to contain "success". As long as this is ''not'' the case it continues checking:
'''Symptom''', in this case from building [[xawtv]]:
+
  while ! (grep "success" /tmp/success)
  /usr/bin/ld: cannot find -lfontconfig
+
do
'''Solution''', in this case for Ubuntu 11.10:
+
  sleep 30
  apt-get install libfontconfig1-dev
+
  done
  
=== libgdk ===
+
The following code checks if the file dblog.log exists. As long as this is not the case it tries to download it via ftp:
'''Symptom''', in this case from running realplay:
+
<source>
  /opt/real/RealPlayer/realplay.bin: error while loading shared libraries: libgdk-x11-2.0.so.0: cannot open shared object file: No such file or directory
+
  while ! (test -e dblog.log); do
'''Reason''': For SUSE Linux, libgdk-x11-2.0.so.0 is provided by the [[package]] libgtk. /usr/lib64/libgdk-x11-2.0.so.0 is provided by the package libgtk-2_0-0-2.24.7-2.5.1.x86_64:
+
  ftp -p ftp://user:password@server/tmp/dblog.log >/dev/null
# [[rpm]] -qf /usr/lib64/libgdk-x11-2.0.so.0
+
  echo -en "."
libgtk-2_0-0-2.24.7-2.5.1.x86_64
+
  sleep 1
/usr/lib/libgdk-x11-2.0.so.0 is provided by the package libgtk-2_0-0-32bit:
+
  done
rpm -qf /usr/lib/libgdk-x11-2.0.so.0
+
</source>
libgtk-2_0-0-32bit-2.24.7-2.5.1.x86_64
 
'''Solution''', in this case for SUSE 12.1:
 
  [[yast]] -i libgtk-2_0-0-32bit
 
  
=== libQt ===
+
== common mistakes ==
'''Problem''', in this case from running [[umtsmon]]:
+
* bash is very picky regarding spaces. There MUST be a space after the ! if it means negation.
./umtsmon: error while loading shared libraries: libqt-mt.so.3: cannot open shared object file: No such file or directory
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i qt3-32bit
 
  
=== libQtGui ===
+
= sending a process to the background =
'''Problem''', in this case from running [[skype]]:
+
To send a process to the [[background]], use the ampersand sign (&):
  skype: error while loading shared libraries: libQtGui.so.4: cannot open shared object file: No such file or directory
+
  firefox & echo "Firefox has been started"
'''Reason''': You do not have the 32bit libraries for Qt.
+
You see a newline is not needed after the &
  
'''Solution''':
+
= forking a process =
  [[yast]] -i libqt4-x11-32bit
+
You can build a process chain using parantheses. This is useful if you want to have two instruction streams being executed in parallel:
 +
<source>
 +
  (find -iname "helloworld.txt") & (sleep 5; echo "Timeout exceeded, killing process"; kill $!)
 +
</source>
  
=== libXaw ===
+
= functions =
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
To define a function in bash, use a non-keyword and append opening and closing parentheses. Here a function greet is defined and it prints "Hello, world!". Then it is called:
  /usr/bin/ld: cannot find -lXaw
+
  # greet()
'''Solution''', in this case for Ubuntu 11.10:
+
{
  apt-get [[install]] libxaw7-dev
+
    echo "Hello, world"
 +
}
 +
  # greet
  
=== libXext ===
+
If you hand over parameters you can greet any planet you like:
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
# greet()
  /usr/bin/ld: cannot find -lXext
+
{
'''Solution''', in this case for Ubuntu 11.10:
+
    echo "Hello, $1"
  apt-get [[install]] libxext-dev
+
}
 +
  # greet Mars
 +
Hello, Mars
 +
# greet World
 +
  Hello, World
  
=== libXm ===
+
= react on CTRL_C =
'''Symptom:''' When installing an rpm (in this case ICAClient) you get an error like
+
The command trap allows you to trap CTRL_C keystrokes so your script will not be aborted
error: Failed dependencies:
+
<source>
        libXm.so.4 is needed by ICAClient-11.0-1.i386
+
#!/bin/bash
'''Solution:''' Install openmotif-libs, best for 32bit and 64bit.
 
  
You can find out what package a file belongs to after installing the rpm like this:
+
trap shelltrap INT
[[rpm]] -qf /usr/lib64/libXm.so.4
 
openmotif-libs-2.3.1-3.13
 
  
=== libXv ===
+
shelltrap()
'''Symptom''', in this case from [[install]]ing realplayer:
+
{
# [[rpm]] -ivh Downloads/RealPlayer11GOLD.rpm
+
    echo "You pressed CTRL_C, but I don't let you escape"
error: Failed dependencies:
+
}
        libXv.so.1 is needed by realplay-11.0.2.1744-1.i386
 
'''Solution''', in this case for SUSE Linux:
 
# [[yast]] -i xorg-x11-libXv-32bit
 
  
=== libxml ===
+
while true; do read line; done
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
</source>
libxml/parser.h: No such file or directory
 
'''Solution''',  in this case for SUSE 11.3:
 
[[yast]] -i libxml-devel
 
  
=== libxml 2 ===
+
;Note: You can still ''pause'' your script by pressing CTRL_Z, send it to the [[background]] and kill it there. To catch CTRL_Z, replace INT by TSTP in the above example. To get an overview of all signals that you might be able to trap, [[open a console]] and enter
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
kill -l
Package libxml-2.0 was not found in the pkg-config search path.
 
Perhaps you should add the directory containing `libxml-2.0.pc'
 
to the PKG_CONFIG_PATH environment variable
 
No package 'libxml-2.0' found
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i libxml2-devel
 
  
=== libXp ===
+
= helpful programs =
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
== awk: read a specific column ==
/usr/bin/ld: cannot find -lXp
+
[[awk]] is a program that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can extract columns from a text. Let's imagine you want to use the [[program]] [[vmstat]] to find out how high the CPU user load was. Here is the output from vmstat:
'''Solution''', in this case for Ubuntu 11.10:
 
apt-get [[install]] libxp-dev
 
  
=== libpng ===
+
<pic src="http://www.linuxintro.org/images/vmstat.png" align=text width=100% caption=VmStat />
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
 
/usr/lib64/gcc/x86_64-suse-linux/4.5/../../../../x86_64-suse-linux/bin/ld: cannot find -lpng
 
collect2: ld returned 1 exit status
 
make: *** [console/scantv] Error 1
 
  
'''Solution''', in this case for SUSE 11.3:
+
We see the user load is in colum 13, and we only want to print this column. We do it with the following command:
  linux-fhbd:~/xawtv # [[yast]] -i libpng14-devel
+
  vmstat 5 | awk '{print $13}'
 +
This will print a line from vmstat all 5 seconds and only write the column 13. It looks like this:
 +
# vmstat 5 | awk '{print $13}'
 +
 +
us
 +
1
 +
1
 +
0
 +
1
 +
To store the CPU user load into a variable we use
 +
load=$(vmstat 1 2 | tail -n 1 | awk '{print $13}')
 +
What happens here? First vmstat outputs some data in its first line. The data about CPU load can only be rubbish because it did not have any time to measure it. So we let it output 2 lines and wait 1 second between them ( => vmstat 1 2 ). From this command we only read the last line ( => tail -n 1 ). From this line we only print column 13 ( => awk '{print $13}' ). This output is stored into the variable $load ( => load=$(...) ).
  
=== lua ===
+
== grep: search a string ==
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
[[grep]] is a [[program]] that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can extract lines that contain a string or match a [[regex]] pattern. Let's imagine you want all external links from www.linuxintro.org's main page:
configure: error: Could not find lua. Lua is needed for some interfaces (rc, telnet, http) as well as many other custom scripts. Use --disable-lua to ignore this error.
+
wget -O linuxintro.txt http://www.linuxintro.org
'''Solution''', in this case for SUSE 11.3:
+
  grep "http:" linuxintro.txt
  [[yast]] -i lua-devel
 
  
=== ncurses ===
+
== sed: replace a string ==
'''Symptom''', in this case from [[build]]ing xawtv:
+
[[sed]] is a [[program]] that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can replace a string by another one. Let's imagine you want to print your distribution's name, but lsd_release outputs too much:
  Oops: (n)curses library not found.  You need this one, please install.
+
  # lsb_release -d
'''Solution''', in this case for SUSE 11.3:
+
Description:   openSUSE 12.1 (x86_64)
  [[yast]] -i ncurses-devel
+
You want to remove this string "Description" so you replace it by nothing:
 +
lsb_release -d | sed "s/Description:\t//"
 +
  openSUSE 12.1 (x86_64)
  
=== Net/DAV/Server.pm ===
+
Once you understand [[regular expressions]] you can use sed with them:
'''Symptom:''' Trying to run a [[perl]] [[program]] you get the message:
 
Can't locate Net/DAV/Server.pm in @INC (@INC contains
 
  
'''Reason:''' Perl has a library of functions, and the module Net/DAV/Server.pm is missing there.
+
* to replace protocol names for a given port (in this case 3200) in /etc/services:
 +
sed -ri "s/.{16}3200/sapdp00 3200/" /etc/services
 +
* if you have an [[apache]] [[web server]] here's how you get the latest websites that have been requested:
 +
<source>
 +
cat /var/log/apache2/access_log | sed ";.*\(GET [^\"]*\).*;\1;"
 +
</source>
  
'''Solution:''' Install Net/DAV/Server.pm as described under [[cpan]].
+
== tr: replace linebreaks ==
 +
[[sed]] is a [[program]] that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can replace a character by another one, even over line breaks.
 +
For example here is how you remove all empty lines from your processor information:
 +
<source>
 +
# cat /proc/cpuinfo | while read a; do ar=$(echo -n $a|tr '\n' ';')
 +
if [ "$ar" <> ";" ]; then echo "$ar"; fi; done
 +
</source>
  
=== pango ===
+
== wc: count ==
'''Symptom''':
+
With the command wc you can count words, characters and lines. wc -l counts lines. For example to find out how many semicolons are in a line, use the following statement:
<pre>
+
while read line
/usr/include/gdk/gdktypes.h:37:25: fatal error: pango/pango.h: No such file or directory
+
do echo "$line" | tr '\n' ' ' | sed "s/;/\n/g" | wc -l
compilation terminated.
+
done
make: *** [gqcam.o] Error 1
+
It lets you input a line of text, counts the semicolons in it and outputs the number.
linux-noqb:~/gqcam-0.8 # cd /usr/include/
 
linux-noqb:/usr/include # find -iname "pango*"
 
./pango-1.0
 
./pango-1.0/pango
 
./pango-1.0/pango/pango-break.h
 
./pango-1.0/pango/pangoft2.h
 
./pango-1.0/pango/pango.h
 
[...]
 
</pre>
 
'''Solution''':
 
linux-noqb:/usr/include # cp -r /usr/include/pango-1.0/pango/ /usr/include/
 
  
=== qt ===
+
How does it do this?
'''Symptom''', in this case from [[build]]ing [http://en.wikipedia.org/wiki/Quassel quassel]:
 
CMake Error at cmake/modules/FindQt4.cmake:1257 (MESSAGE):
 
  Qt qmake not found!
 
  
'''Reason''': You are missing the qt build environment
+
It reads lines from your keyboard (while read line). It outputs the line (echo "$line"), but it does not output it in the console. The pipe (|) redirects the output to the input stream of the command tr. The command tr replaces the ENTER ('\
 +
') by a space (' '). The pipe (|) redirects the output to the input stream of sed. sed substitutes ("s/) the semicolon (;) by (/) a linefeed (\
 +
), globally (/g"). The pipe redirects the output to the input stream of the wc -l command that outputs the count of lines.
  
'''Solution''', in this case for SUSE Linux 11.4:
+
== dialog: create dialogs ==
[[yast]] -i libqt4-devel
+
Dialog is a command that helps you creating dialogs in the shell. The answers given by the user are send to [[stderr]] and/or influence the command's return code. For example if you run this script:
 +
#!/bin/bash
 +
if (dialog --title "Message"  --yesno "Are you having fun?" 6 25)
 +
then echo "glad you have fun"
 +
else echo "sad you don't have fun"
 +
fi
 +
It will display this dialog:
  
=== ssh does not work ===
+
[[File:snapshot-dialog.png]]
'''Symptom:''' when calling a GUI program within an ssh -X session, you get an error message like this:
 
X Error of failed request:  BadAtom (invalid Atom parameter)
 
  Major opcode of failed request:  20 (X_GetProperty)
 
  Atom id in failed request:  0x17
 
  Serial number of failed request:  4
 
  Current serial number in output stream:  4
 
  
'''Solution:''' Exit the session, reconnect with ssh -Y
+
This has been taken from http://www.linuxjournal.com/article/2807. Read there for more info.
  
=== unary operator expected ===
+
= See also =
'''Symptom''' when running a [[program]] you get an error message like
+
* [[bash]]
test.sh: line 4: [: =: unary operator expected
+
* [[shell]]
 
+
* [[scripting]]
'''Reason''' See [[what does "unary operator expected" mean]].
+
* [[bash operators]]
 
+
* http://en.wikibooks.org/wiki/Bash_Shell_Scripting
=== xclock not found ===
+
* http://ryanstutorials.net/linuxtutorial/scripting.php
'''Symptom:''' You cannot call xclock. When you [[open a console]] and do it you get the message
+
* http://wiki.linuxquestions.org/wiki/Bash_tips
xclock: command not found
+
* http://wiki.linuxquestions.org/wiki/Bash
'''Solution:''' [[Install]] xclock's [[package]], in this case with SUSE Linux 12.1:
+
* http://linuxconfig.org/Bash_scripting_Tutorial
yast -i xorg-x11
+
* http://steve-parker.org/sh/intro.shtml
 +
* http://mywiki.wooledge.org/BashFAQ
 +
* http://mywiki.wooledge.org/BashPitfalls
  
=== zlib ===
+
[http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.linuxintro.org%2Fwiki%2FShell_scripting_tutorial&t=Shell%20scripting%20Tutorial&src=sp Share on Facebook]
'''Symptom''', in this case from [[build]]ing [[freeciv]]:
 
checking for gzgets in -lz... no
 
configure: error: Could not find zlib library.
 
'''Reason:''' Your '''''z'''''ipping library ''zlib'' is not [[install]]ed in a way that you can build [[software]] with [[dependencies]] on it. You need the development [[package]] of zlib.
 
  
'''Solution''', in this case for SUSE Linux:
+
<stumbleuponbutton />
[[yast]] -i zlib-devel
 
  
= See also =
+
[[Category:Mindmap]]
* [[dependencies]]
+
[[Category:Learning]]
* [[troubleshooting]]
 

Revision as of 08:06, 30 March 2020


BaBE - Bash By Examples; Your significant Linux scripting tutorial;;

MindMap

Hello world

The easiest way to get your feet wet with a programming language is to start with a program that simply outputs a trivial text, the so-called hello-world-example. Here it is for bash:

  • create a file named hello in your home directory with the following content:
#!/bin/bash
echo "Hello, world!"
cd
chmod +x hello
  • now you can execute your file like this:
# ./hello
Hello, world!
  • or like this:
# bash hello
Hello, world!

You see - the output of your shell program is the same as if you had entered the commands into a console.

calling commands

In your shell script you can call every command that you can call when opening a console: <source>

echo "This is a directory listing, latest modified files at the bottom:"
ls -ltr
echo "Now calling a browser"
firefox
echo "Continuing with the script"

</source>

variables

input

To show you how to deal with variables, we will now write a script that asks for your name and greets you:

echo "what is your name? "
read name
echo "hello $name"

You see that the name is stored in a variable $name. Note the quotation marks " around "hello $name". By using these you say that you want variables to be replaced by their content. If you were to use apostrophes, the name would not be printed, but $name instead.

${}

The ${} operator stands for the variable, there is no difference if you write

echo "$name"

or

echo "${name}"

So what is the sense of this? Imagine you want to echo a string directly, without any blank, after the content of a variable: <source>

echo "if I add the syllable owa to your name it will be ${name}owa"

</source>

common mistakes

Note that the variable is called $name, however the correct statement to read it from the keyboard is

read name

It is a common mistake to write

read $name

which means "read a string and store it into the variable whose name is stored in $name"

parameters

<source> echo "Here are all parameters you called this script with: $@" echo "Here is parameter 1: $1" echo "Which parameter do you want to be shown? " read number args=("$@") echo "${args[$number-1]}" </source>

return codes

Every bash script can communicate with the rest of the system by

  • sending data to stdout
  • sending data to stderr
  • delivering a return code

The return code is 0 if everything worked well. You can query it for the most recent command using $?: <source>

bootstick@bootstick:~$ echo "hello world"; echo $?
hello world
0
bootstick@bootstick:~$ echo "hello world">/proc/cmdline; echo $?
bash: /proc/cmdline: Permission denied
1

</source>

In bash, true is 0 and false is any value but 0. There exist two commands, true and false that deliver true or false, respectively:

bootstick@bootstick:~$ true; echo $?
0
bootstick@bootstick:~$ false; echo $?
1

line feeds

Let's look at the following script:

read name
if [ $name = "Thorsten" ]; then echo "I know you"; fi

Instead of a semicolon you can write a line feed like this:

read name
if [ $name = "Thorsten" ]
  then echo "I know you"
fi

And instead of a line feed you can use a semicolon:

read name; if [ $name = "Thorsten" ]; then echo "I know you"; fi

If you want to insert a line feed where you do not need one, e.g. to make the code better readable, you must prepend it with a backslash:

read \
  name
if [ $name = "Thorsten" ]
  then \
    echo "I know you"
fi

storing a command's output

To read a command's output into a variable use $(), backticks or piping.

$()

arch=$(uname -m)
echo "Your system is a $arch system."

backticks

arch=`uname -m`
echo "Your system is a $arch system."

piping

Piping is a very elegant concept in the Linux world. It allows you to take one command's output and use it as input for the next command. Now you can divide tasks into smaller tasks. For example instead of having a program counting all files in a directory you use one program (ls) to list all files in a directory and one program (wc) to count the lines: <source>

ls | wc -l

</source> You can also put the output into a variable, in this case $arch: <source>

uname -m | while read arch; do echo "Your system is a $arch system."; done

</source>

comparison

The advantage of using backticks over $() is that backticks also work in the sh shell. The advantage of using $() over backticks is that you can cascade them. In the example below we use this possibility to get a list of all files installed with rpm on the system:

filelist=$(rpm -ql $(rpm -qa))

You can use the piping approach if you need to cascade in sh, but this is not focus of this bash tutorial.

common mistakes

Usually unexperienced programmers try something like

uname -m | read arch

which does not work. You must embed the read into a while loop.

conditions

The easiest form of a condition in bash is this if example:

echo "what is your name? "
read name
if [ $name = "Thorsten" ]; then echo "I know you"; fi

Now let's look closer at this, why does it work? Why is there a blank needed behind the [ sign? The answer is that [ is just an ordinary command in the shell. It delivers a return code for the expression that follows till the ] sign. To prove this we can write a script: <source>

if true; then echo "the command following if true is being executed"; fi
if false; then echo "this will not be shown"; fi

</source>

empty strings

An empty string evaluates to false inside the [ ] operators so it is possible to check if a string result is empty like this:

# result=
# if [ $result ]; then echo success; fi
# result=good
# if [ $result ]; then echo success; fi
success

arithmetic expressions

You can compare integer numbers like this:

echo "what is your age? "
read age
if (( $age >= 21 )); then echo "Let's talk about sex."; fi

However bash does not understand floating point numbers. To compare floating numbers you will use external programs such as bc: <source>

$ if [ $(echo "2.1<2.2"|bc) = 1 ]; then echo "correct"; else echo "wrong"; fi
correct
$ if [ $(echo "2.1>2.2"|bc) = 1 ]; then echo "correct"; else echo "wrong"; fi
wrong

</source>

not equal

To check if a variable is NOT equal to whatever, use !=: <source>

if [ "$LANG" != "C" ]; then echo "please set your system lanugage to C"; fi

</source>

common mistakes

Common mistakes are:

Redirections

To redirect the output of a command to a file you have to consider that there are two output streams in UNIX, stdout and stderr.

filling files

To create a file, probably the easiest way is to use cat. The following example writes text into README till a line occurs that only contains the string "EOF":

cat >README<<EOF
This is line 1
This is line 2
This is the last line
EOF

Afterwards, README will contain the 3 lines below the cat command and above the line with EOF.

loops

for loops

Here is an example for a for-loop. It makes a backup of all text files:

for i in *.txt; do cp $i $i.bak; done

The above command takes each .txt file in the current directory, stores it in the variable $i and copies it to $i.bak. So file.txt gets copied to file.txt.bat.

You can also use subsequent numbers as a for loop using the command seq like this:

for i in $(seq 1 1 3); do echo $i; done

while loops

$ while true; do read line; done

negations

You can negate a result with the ! operator. $? is the last command's return code:

# true
# echo $?
0
# false
# echo $?
1
# ! true
# echo $?
1
# ! false
# echo $?
0

So you get an endless loop out of:

while ! false; do echo hallo; done

The following code checks the file /tmp/success to contain "success". As long as this is not the case it continues checking:

while ! (grep "success" /tmp/success)
do
  sleep 30
done

The following code checks if the file dblog.log exists. As long as this is not the case it tries to download it via ftp: <source>

while ! (test -e dblog.log); do
  ftp -p ftp://user:password@server/tmp/dblog.log >/dev/null
  echo -en "."
  sleep 1
done

</source>

common mistakes

  • bash is very picky regarding spaces. There MUST be a space after the ! if it means negation.

sending a process to the background

To send a process to the background, use the ampersand sign (&):

firefox & echo "Firefox has been started"

You see a newline is not needed after the &

forking a process

You can build a process chain using parantheses. This is useful if you want to have two instruction streams being executed in parallel: <source>

(find -iname "helloworld.txt") & (sleep 5; echo "Timeout exceeded, killing process"; kill $!)

</source>

functions

To define a function in bash, use a non-keyword and append opening and closing parentheses. Here a function greet is defined and it prints "Hello, world!". Then it is called:

# greet()
{
    echo "Hello, world"
}
# greet

If you hand over parameters you can greet any planet you like:

# greet()
{
    echo "Hello, $1"
}
# greet Mars
Hello, Mars
# greet World
Hello, World

react on CTRL_C

The command trap allows you to trap CTRL_C keystrokes so your script will not be aborted <source>

  1. !/bin/bash

trap shelltrap INT

shelltrap() {

   echo "You pressed CTRL_C, but I don't let you escape"

}

while true; do read line; done </source>

Note
You can still pause your script by pressing CTRL_Z, send it to the background and kill it there. To catch CTRL_Z, replace INT by TSTP in the above example. To get an overview of all signals that you might be able to trap, open a console and enter
kill -l

helpful programs

awk: read a specific column

awk is a program that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can extract columns from a text. Let's imagine you want to use the program vmstat to find out how high the CPU user load was. Here is the output from vmstat:

VmStat

We see the user load is in colum 13, and we only want to print this column. We do it with the following command:

vmstat 5 | awk '{print $13}'

This will print a line from vmstat all 5 seconds and only write the column 13. It looks like this:

# vmstat 5 | awk '{print $13}'

us
1
1
0
1

To store the CPU user load into a variable we use

load=$(vmstat 1 2 | tail -n 1 | awk '{print $13}')

What happens here? First vmstat outputs some data in its first line. The data about CPU load can only be rubbish because it did not have any time to measure it. So we let it output 2 lines and wait 1 second between them ( => vmstat 1 2 ). From this command we only read the last line ( => tail -n 1 ). From this line we only print column 13 ( => awk '{print $13}' ). This output is stored into the variable $load ( => load=$(...) ).

grep: search a string

grep is a program that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can extract lines that contain a string or match a regex pattern. Let's imagine you want all external links from www.linuxintro.org's main page:

wget -O linuxintro.txt http://www.linuxintro.org
grep "http:" linuxintro.txt 

sed: replace a string

sed is a program that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can replace a string by another one. Let's imagine you want to print your distribution's name, but lsd_release outputs too much:

# lsb_release -d
Description:    openSUSE 12.1 (x86_64)

You want to remove this string "Description" so you replace it by nothing:

lsb_release -d | sed "s/Description:\t//"
openSUSE 12.1 (x86_64)

Once you understand regular expressions you can use sed with them:

  • to replace protocol names for a given port (in this case 3200) in /etc/services:
sed -ri "s/.{16}3200/sapdp00 3200/" /etc/services
  • if you have an apache web server here's how you get the latest websites that have been requested:

<source>

cat /var/log/apache2/access_log | sed ";.*\(GET [^\"]*\).*;\1;"

</source>

tr: replace linebreaks

sed is a program that is installed on almost all Linux distributions. It is a good helper for text stream processing. It can replace a character by another one, even over line breaks. For example here is how you remove all empty lines from your processor information: <source>

# cat /proc/cpuinfo | while read a; do ar=$(echo -n $a|tr '\n' ';')
if [ "$ar" <> ";" ]; then echo "$ar"; fi; done

</source>

wc: count

With the command wc you can count words, characters and lines. wc -l counts lines. For example to find out how many semicolons are in a line, use the following statement:

while read line
do echo "$line" | tr '\n' ' ' | sed "s/;/\n/g" | wc -l
done

It lets you input a line of text, counts the semicolons in it and outputs the number.

How does it do this?

It reads lines from your keyboard (while read line). It outputs the line (echo "$line"), but it does not output it in the console. The pipe (|) redirects the output to the input stream of the command tr. The command tr replaces the ENTER ('\ ') by a space (' '). The pipe (|) redirects the output to the input stream of sed. sed substitutes ("s/) the semicolon (;) by (/) a linefeed (\ ), globally (/g"). The pipe redirects the output to the input stream of the wc -l command that outputs the count of lines.

dialog: create dialogs

Dialog is a command that helps you creating dialogs in the shell. The answers given by the user are send to stderr and/or influence the command's return code. For example if you run this script:

#!/bin/bash
if (dialog --title "Message"  --yesno "Are you having fun?" 6 25)
then echo "glad you have fun"
else echo "sad you don't have fun"
fi

It will display this dialog:

Snapshot-dialog.png

This has been taken from http://www.linuxjournal.com/article/2807. Read there for more info.

See also

Share on Facebook