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"
  
=== certificate.pem ===
+
= parameters =
'''Symptom:''' A program, e.g. [[sHellinaBox]] outputs the error message:
+
<source>
Cannot read valid certificate from "certificate.pem". Check file permissions and file format.
+
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>
  
'''Reason,''' in this case for [[sHellInaBox]]: The program cannot create certificate.pem in the current folder
+
= 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>
  
'''Solution,''' in this case for [[shellInABox]]: start the program in /tmp
+
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
  
=== DBUS ===
+
= line feeds =
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
Let's look at the following script:
  configure: error: Couldn't find DBus >= 1.0.0, install libdbus-dev ?
+
read name
'''Solution''', in this case for SUSE 11.3:
+
if [ $name = "Thorsten" ]; then echo "I know you"; fi
  [[yast]] -i dbus-1-devel
+
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
  
=== firefox ===
+
= storing a command's output =
'''Symptom:''' When trying to start [[firefox]] you get a message:
+
To read a command's output into a variable use $(), backticks or [[piping]].
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.
 
  
'''Solution''', in this case for SUSE Linux 12.1:
+
== $() ==
[[open a console]] and enter the [[command]]
+
arch=$(uname -m)
  killall firefox-bin
+
  echo "Your system is a $arch system."
  
=== fribidi ===
+
== backticks ==
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
  arch=`uname -m`
  [[configure]]: error: Package requirements (fribidi) were not met:
+
  echo "Your system is a $arch system."
 
No package 'fribidi' found
 
 
Consider adjusting the PKG_CONFIG_PATH environment variable if you
 
  installed software in a non-standard prefix.
 
 
Alternatively, you may set the environment variables FRIBIDI_CFLAGS
 
and FRIBIDI_LIBS to avoid the need to call pkg-config.
 
See the pkg-config man page for more details.
 
'''Solution''', in this case for SUSE 11.3:
 
[[yast]] -i fribidi-devel
 
  
=== gcrypt ===
+
== piping ==
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
[[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:
configure: error: libgcrypt version 1.1.94 or higher not found. Install libgcrypt or use --disable-libgcrypt. Have a nice day.
+
<source>
'''Solution''', in this case for SUSE 11.3:
+
ls | wc -l
  [[yast]] -i libgcrypt-devel
+
</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>
  
=== gdk ===
+
== comparison ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
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:
/usr/include/gtk/gtk.h:32:21: fatal error: gdk/gdk.h: No such file or directory
+
  filelist=$([[rpm]] -ql $(rpm -qa))
'''Solution''', in this case for SUSE Linux 11.3:
+
You can use the piping approach if you need to cascade in sh, but this is not focus of this bash tutorial.
  [[cp]] -pr /usr/include/gtk-2.0/gdk /usr/include/
 
  
=== gdkconfig ===
+
== common mistakes ==
'''Symptom''':
+
Usually unexperienced programmers try something like
  /usr/include/gdk/gdktypes.h:55:23: fatal error: gdkconfig.h: No such file or directory
+
  uname -m | read arch
compilation terminated.
+
which [http://mywiki.wooledge.org/BashFAQ/024 does not work]. You must embed the read into a while loop.
[[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 ===
+
= conditions =
'''Symptom''':
+
The easiest form of a condition in bash is this '''if''' example:
  /usr/include/gdk/gdkpixbuf.h:37:35: fatal error: gdk-pixbuf/gdk-pixbuf.h: No such file or directory
+
  echo "what is your name? "
  compilation terminated.
+
  read name
  [[make]]: *** [gqcam.o] Error 1
+
  if [ $name = "Thorsten" ]; then echo "I know you"; fi
'''Solution''':
+
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:
<pre>
+
<source>
linux-noqb:~/gqcam-0.8 # cd /usr/include/
+
if true; then echo "the command following if true is being executed"; fi
linux-noqb:/usr/include # find -iname "gdk-pixbuf*"
+
if false; then echo "this will not be shown"; fi
./gtk-2.0/gdk-pixbuf
+
</source>
./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 ===
+
== empty strings ==
'''Symptom''', in this example from [[build]]ing [[pidgin]]:
+
An empty string evaluates to false inside the [ ] operators so it is possible to check if a string ''result'' is empty like this:
  [[configure]]: error: GNU gettext tools not found; required for intltool
+
  # result=
'''Solution''', in this case for SLES 11:
+
# if [ $result ]; then echo success; fi
  # [[yast]] -i gettext-tools
+
# result=good
 +
  # if [ $result ]; then echo success; fi
 +
success
  
=== gio ===
+
== arithmetic expressions ==
'''Symptom''', in this case [[build]]ing from gqcam:
+
You can compare integer numbers like this:
  /usr/include/gdk/gdkapplaunchcontext.h:30:21: fatal error: gio/gio.h: No such file or directory
+
  echo "what is your age? "
'''Solution''', in this case for SUSE Linux 11.3:
+
read age
  [[cp]] -r /usr/include/glib-2.0/gio/ /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>
  
=== glib ===
+
== not equal ==
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
To check if a variable is NOT equal to whatever, use !=:
error: glib.h: No such file or directory
+
<source>
'''Solution''' (in this case for SUSE 11.3):
+
  if [ "$LANG" != "C" ]; then echo "please set your system lanugage to C"; fi
  [[yast]] -i glib2-devel
+
</source>
[[cp]] /usr/include/glib-2.0/glib.h /usr/include/
 
cp -pr /usr/include/glib-2.0/glib /usr/include/
 
  
=== glibconfig ===
+
== common mistakes ==
'''Symptom''', in this case from [[build]]ing gqcam:
+
Common mistakes are:
/usr/include/glib/gtypes.h:34:24: fatal error: glibconfig.h: No such file or directory
+
* to forget the blank behind/before the [ or ] character
'''Solution''', in this case for SUSE 11.3:
+
* to forget the blank behind/before the equal sign
[[cp]] /usr/lib64/glib-2.0/include/glibconfig.h /usr/include/
+
* see [[what does "unary operator expected" mean]]
  
=== gmodule ===
+
= Redirections =
'''Symptom''', in this case from [[build]]ing gqcam:
+
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]].
/usr/include/gio/giomodule.h:31:21: fatal error: gmodule.h: No such file or directory
 
'''Solution''', in this case for SUSE 11.3:
 
[[cp]] /usr/include/glib-2.0/gmodule.h /usr/include/
 
  
=== gtk ===
+
= filling files =
'''Symptom''', in this case from [[build]]ing [[kino]]:
+
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":
  checking for GTK2... configure: error: Package requirements (gthread-2.0 libglade-2.0 >= 2.5.0 gtk+-2.0 >= 2.6) were not met:
+
  cat >README<<EOF
   
+
This is line 1
  No package 'libglade-2.0' found
+
This is line 2
'''Solution''', in this case for SUSE 11.3:
+
  This is the last line
[[yast]] -i libglade2-devel
+
  EOF
 +
Afterwards, README will contain the 3 lines below the cat command and above the line with EOF.
  
=== gtk-config ===
+
= loops =
'''Symptom''', in this case from [[build]]ing gqcam:
 
/bin/sh: gtk-config: command not found
 
gqcam.c:32:21: fatal error: gtk/gtk.h: No such file or directory
 
'''Solution''', in this case for SUSE 11.3:
 
* install gtk 2.20
 
* copy the header files
 
[[cp]] -pr /usr/include/gtk-2.0/gtk/ /usr/include
 
  
=== gtk-window-dialog ===
+
== for loops ==
<pre>
+
Here is an example for a for-loop. It makes a [[backup]] of all text files:
frontend.c:411:44: error: ‘GTK_WINDOW_DIALOG’ undeclared (first use in this function)
+
for i in *.txt; do [[cp]] $i $i.bak; done
frontend.c:411:44: note: each undeclared identifier is reported only once for each function it appears in
+
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.
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 ===
+
You can also use subsequent numbers as a for loop using the command seq like this:
'''Symptom''', in this case from [[build]]ing [[pidgin]]:
+
  for i in $([[seq]] 1 1 3); do [[echo]] $i; done
  [[configure]]: error: The intltool scripts were not found. Please install intltool.
 
'''Solution''', in this case with SLES 11:
 
# [[wget]] http://ftp.gnome.org/pub/gnome/sources/intltool/0.35/intltool-0.35.5.tar.bz2
 
# bunzip2 intltool-0.35.5.tar.bz2
 
# [[tar]] xvf intltool-0.35.5.tar
 
# [[cd]] intltool-0.35.5/
 
# ./[[configure]] && [[make]] -j8 && make [[install]]
 
  
=== jpeg ===
+
== while loops ==
'''Symptom''', in this case from [[xawtv]]:
+
  $ while true; do read line; done
Oops:  jpeg library not found.  You need this one, please install.
 
'''Solution''', in this case for SUSE 11.3:
 
  [[yast]] -i libjpeg-devel
 
  
=== KDE ===
+
= negations =
'''Symptom''':
+
You can negate a result with the ! operator. $? is the last command's return code:
  ERROR: Could not find KDE4 kde4-config
+
# true
'''Solution''', e.g. under Debian:
+
# echo $?
  apt-get [[install]] kdelibs5-dev
+
0
 +
# false
 +
# echo $?
 +
1
 +
# ! true
 +
# echo $?
 +
1
 +
# ! false
 +
# echo $?
 +
0
 +
So you get an endless loop out of:
 +
  while ! false; do echo hallo; done
  
=== liblavdisplay ===
+
The following code checks the file /tmp/success to contain "success". As long as this is ''not'' the case it continues checking:
'''Symptom''', e.g. when compiling mjpegtools:
+
  while ! (grep "success" /tmp/success)
  ./.libs/liblavplay.so: undefined reference to `XOpenDisplay'
+
do
'''Solution''', e.g. under SUSE:
+
  sleep 30
  [[yast]] -i libSDL-devel
+
  done
  
=== libQtDBus ===
+
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 [[skype]]:
+
<source>
  skype: error while loading shared libraries: libQtDBus.so.4: cannot open shared object file: No such file or directory
+
  while ! (test -e dblog.log); do
'''Reason''': You do not have the 32bit libraries for Qt.
+
  ftp -p ftp://user:password@server/tmp/dblog.log >/dev/null
 +
  echo -en "."
 +
  sleep 1
 +
done
 +
</source>
  
'''Solution''', in this case for SUSE 11.3:
+
== common mistakes ==
[[yast]] -i libqt4-32bit
+
* bash is very picky regarding spaces. There MUST be a space after the ! if it means negation.
  
=== libfontconfig ===
+
= sending a process to the background =
'''Symptom''', in this case from building [[xawtv]]:
+
To send a process to the [[background]], use the ampersand sign (&):
  /usr/bin/ld: cannot find -lfontconfig
+
  firefox & echo "Firefox has been started"
'''Solution''', in this case for Ubuntu 11.10:
+
You see a newline is not needed after the &
apt-get install libfontconfig1-dev
 
  
=== libgdk ===
+
= forking a process =
'''Symptom''', in this case from running realplay:
+
You can build a process chain using parantheses. This is useful if you want to have two instruction streams being executed in parallel:
/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
+
<source>
'''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:
+
  (find -iname "helloworld.txt") & (sleep 5; echo "Timeout exceeded, killing process"; kill $!)
# [[rpm]] -qf /usr/lib64/libgdk-x11-2.0.so.0
+
</source>
libgtk-2_0-0-2.24.7-2.5.1.x86_64
 
/usr/lib/libgdk-x11-2.0.so.0 is provided by the package libgtk-2_0-0-32bit:
 
rpm -qf /usr/lib/libgdk-x11-2.0.so.0
 
  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 ===
+
= functions =
'''Problem''', in this case from running [[umtsmon]]:
+
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:
./umtsmon: error while loading shared libraries: libqt-mt.so.3: cannot open shared object file: No such file or directory
+
# greet()
'''Solution''', in this case for SUSE 11.3:
+
{
  [[yast]] -i qt3-32bit
+
    echo "Hello, world"
 +
}
 +
  # greet
  
=== libQtGui ===
+
If you hand over parameters you can greet any planet you like:
'''Problem''', in this case from running [[skype]]:
+
# greet()
  skype: error while loading shared libraries: libQtGui.so.4: cannot open shared object file: No such file or directory
+
{
'''Reason''': You do not have the 32bit libraries for Qt.
+
    echo "Hello, $1"
 +
}
 +
# greet Mars
 +
Hello, Mars
 +
  # greet World
 +
Hello, World
  
'''Solution''':
+
= react on CTRL_C =
[[yast]] -i libqt4-x11-32bit
+
The command trap allows you to trap CTRL_C keystrokes so your script will not be aborted
 +
<source>
 +
#!/bin/bash
  
=== libXaw ===
+
trap shelltrap INT
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
 
/usr/bin/ld: cannot find -lXaw
 
'''Solution''', in this case for Ubuntu 11.10:
 
apt-get [[install]] libxaw7-dev
 
  
=== libXext ===
+
shelltrap()
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
{
/usr/bin/ld: cannot find -lXext
+
    echo "You pressed CTRL_C, but I don't let you escape"
'''Solution''', in this case for Ubuntu 11.10:
+
}
apt-get [[install]] libxext-dev
 
  
=== libXm ===
+
while true; do read line; done
'''Symptom:''' When installing an rpm (in this case ICAClient) you get an error like
+
</source>
error: Failed dependencies:
 
        libXm.so.4 is needed by ICAClient-11.0-1.i386
 
'''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:
+
;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
[[rpm]] -qf /usr/lib64/libXm.so.4
+
  kill -l
  openmotif-libs-2.3.1-3.13
 
  
=== libXv ===
+
= helpful programs =
'''Symptom''', in this case from [[install]]ing realplayer:
+
== awk: read a specific column ==
# [[rpm]] -ivh Downloads/RealPlayer11GOLD.rpm
+
[[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:
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 ===
+
<pic src="http://www.linuxintro.org/images/vmstat.png" align=text width=100% caption=VmStat />
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
 
libxml/parser.h: No such file or directory
 
'''Solution''',  in this case for SUSE 11.3:
 
[[yast]] -i libxml-devel
 
  
=== libxml 2 ===
+
We see the user load is in colum 13, and we only want to print this column. We do it with the following command:
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
vmstat 5 | awk '{print $13}'
  Package libxml-2.0 was not found in the pkg-config search path.
+
This will print a line from vmstat all 5 seconds and only write the column 13. It looks like this:
  Perhaps you should add the directory containing `libxml-2.0.pc'
+
# vmstat 5 | awk '{print $13}'
  to the PKG_CONFIG_PATH environment variable
+
   
  No package 'libxml-2.0' found
+
  us
'''Solution''', in this case for SUSE 11.3:
+
1
[[yast]] -i libxml2-devel
+
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=$(...) ).
  
=== libXp ===
+
== grep: search a string ==
'''Symptom''', in this case from [[build]]ing [[xawtv]]:
+
[[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:
  /usr/bin/ld: cannot find -lXp
+
  wget -O linuxintro.txt http://www.linuxintro.org
'''Solution''', in this case for Ubuntu 11.10:
+
  grep "http:" linuxintro.txt
  apt-get [[install]] libxp-dev
 
  
=== libpng ===
+
== 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:
/usr/lib64/gcc/x86_64-suse-linux/4.5/../../../../x86_64-suse-linux/bin/ld: cannot find -lpng
+
# lsb_release -d
  collect2: ld returned 1 exit status
+
  Description:   openSUSE 12.1 (x86_64)
  make: *** [console/scantv] Error 1
+
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)
  
'''Solution''', in this case for SUSE 11.3:
+
Once you understand [[regular expressions]] you can use sed with them:
linux-fhbd:~/xawtv # [[yast]] -i libpng14-devel
 
  
=== lua ===
+
* to replace protocol names for a given port (in this case 3200) in /etc/services:
'''Symptom''', in this case from [[build]]ing [[vlc]]:
+
sed -ri "s/.{16}3200/sapdp00 3200/" /etc/services
  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.
+
* if you have an [[apache]] [[web server]] here's how you get the latest websites that have been requested:
'''Solution''', in this case for SUSE 11.3:
+
<source>
[[yast]] -i lua-devel
+
  cat /var/log/apache2/access_log | sed ";.*\(GET [^\"]*\).*;\1;"
 +
</source>
  
=== ncurses ===
+
== tr: replace linebreaks ==
'''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 character by another one, even over line breaks.
  Oops: (n)curses library not found.  You need this one, please install.
+
For example here is how you remove all empty lines from your processor information:
'''Solution''', in this case for SUSE 11.3:
+
<source>
  [[yast]] -i ncurses-devel
+
  # cat /proc/cpuinfo | while read a; do ar=$(echo -n $a|tr '\n' ';')
 +
  if [ "$ar" <> ";" ]; then echo "$ar"; fi; done
 +
</source>
  
=== Net/DAV/Server.pm ===
+
== wc: count ==
'''Symptom:''' Trying to run a [[perl]] [[program]] you get the message:
+
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:
  Can't locate Net/DAV/Server.pm in @INC (@INC contains
+
  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.
  
'''Reason:''' Perl has a library of functions, and the module Net/DAV/Server.pm is missing there.
+
How does it do this?
  
'''Solution:''' Install Net/DAV/Server.pm as described under [[cpan]].
+
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.
  
=== pango ===
+
== dialog: create dialogs ==
'''Symptom''':
+
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:
<pre>
+
#!/bin/bash
/usr/include/gdk/gdktypes.h:37:25: fatal error: pango/pango.h: No such file or directory
+
if (dialog --title "Message" --yesno "Are you having fun?" 6 25)
compilation terminated.
+
then echo "glad you have fun"
make: *** [gqcam.o] Error 1
+
else echo "sad you don't have fun"
linux-noqb:~/gqcam-0.8 # cd /usr/include/
+
  fi
linux-noqb:/usr/include # find -iname "pango*"
+
It will display this dialog:
./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/
 
  
=== python.h ===
+
[[File:snapshot-dialog.png]]
'''Symptom''', in this case from setting up [[uniconvertor]]:
 
src/modules/filter/streamfilter.c:24:20: fatal error: Python.h: No such file or directory
 
'''Solution''', in this case for SUSE Linux 12.1:
 
[[yast]] -i python-devel
 
  
=== qt ===
+
This has been taken from http://www.linuxjournal.com/article/2807. Read there for more info.
'''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
+
= See also =
 
+
* [[bash]]
'''Solution''', in this case for SUSE Linux 11.4:
+
* [[shell]]
[[yast]] -i libqt4-devel
+
* [[scripting]]
 
+
* [[bash operators]]
=== ssh does not work ===
+
* http://en.wikibooks.org/wiki/Bash_Shell_Scripting
'''Symptom:''' when calling a GUI program within an ssh -X session, you get an error message like this:
+
* http://ryanstutorials.net/linuxtutorial/scripting.php
X Error of failed request: BadAtom (invalid Atom parameter)
+
* http://wiki.linuxquestions.org/wiki/Bash_tips
  Major opcode of failed request: 20 (X_GetProperty)
+
* http://wiki.linuxquestions.org/wiki/Bash
  Atom id in failed request: 0x17
+
* http://linuxconfig.org/Bash_scripting_Tutorial
  Serial number of failed request: 4
+
* http://steve-parker.org/sh/intro.shtml
  Current serial number in output stream:  4
+
* http://mywiki.wooledge.org/BashFAQ
 
+
* http://mywiki.wooledge.org/BashPitfalls
'''Solution:''' Exit the session, reconnect with ssh -Y
 
 
 
=== unary operator expected ===
 
'''Symptom''' when running a [[program]] you get an error message like
 
test.sh: line 4: [: =: unary operator expected
 
  
'''Reason''' See [[what does "unary operator expected" mean]].
+
[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]
  
=== xclock not found ===
+
<stumbleuponbutton />
'''Symptom:''' You cannot call xclock. When you [[open a console]] and do it you get the message
 
xclock: command not found
 
'''Solution:''' [[Install]] xclock's [[package]], in this case with SUSE Linux 12.1:
 
yast -i xorg-x11
 
  
=== Xlib ===
+
[[Category:Mindmap]]
'''Symptom''', in this case from [[build]]ing [[fsl]]:
+
[[Category:Learning]]
error: X11/Xlib.h: No such file or directory
 
'''Solution''', in this case for CentOs 6:
 
yum install libX11-devel
 
 
 
=== zlib ===
 
'''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:
 
[[yast]] -i zlib-devel
 
 
 
= See also =
 
* [[dependencies]]
 
* [[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