Linux shell script which

How do I find out what shell I am using on Linux/Unix?

B oth Linux and Unix provides various shell out of the box. One can find bash (Bourne Again shell), ksh (Korn shell), csh (C shell)/tcsh (TC shell), sh (Bourne shell) and more installed by default. However, how do you check which shell am I using? What is the best way to find out what shell I am using on Linux? The echo $SHELL is not so reliable. This page explains how to find out which shell I am using at a Linux, MacOS, FreeBSD, or Unix-like systems.

How can I find out what shell I am using?

The following echo command or printf command should work:
echo «$SHELL»
OR
printf «My current shell — %s\n» «$SHELL»
Please note that $SHELL is the shell for the current user but not necessarily the shell that is running at the moment. Try the following examples

How do I check which shell am I using?

Here is another old good Unix trick. Use the ps command with -p option. The following command selects the processes whose process ID numbers appear in pid. Use the following command to find out which shell you are in:
ps -p $$
Sample outputs:

So what is a $ argument passed to the -p option? Remember $ returns the PID (process identification number) of the current process, and the current process is your shell. So running a ps on that number displays a process status listing of your shell. In that listing, you will find the name of your shell (look for CMD column).
ps -p $$
Sample outputs:

From my Linux box:
ps -p $$
Sample outputs:

You can store your shell name in a variable as follows :
MYSHELL=`ps -hp $$|awk ‘‘`
Please note those are backquotes, not apostrophes. Or better try out the following if you have a bash shell:
MYSHELL=$(ps -hp $$|awk ‘‘)
Another option is as follows:
echo $0
OR
printf «%s\n» $0
Sample outputs from the above commands:

Fig.01: Linux check which shell am I using

How do I check how many shells are installed on my Linux box?

The /etc/shells is a text file which contains the full pathnames of valid login shells. Type the following [nixmd name=”cat”] to see list how many shells are installed on your Linux or Unix box:
cat /etc/shells

Use /etc/shells file to check how many shells are installed on your system

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Okay, so when I open the Terminal app, which shell is opened by default?

Your default shell is defined in /etc/passwd file. So try the following grep command:

How to check which shell am I using:

Use the following Linux or Unix commands:

  1. ps -p $$ – Display your current shell name reliably.
  2. echo «$SHELL» – Print the shell for the current user but not necessarily the shell that is running at the movement.
  3. echo $0 – Another reliable and simple method to get the current shell interpreter name on Linux or Unix-like systems.
  4. readlink /proc/$$/exe – Another option to get the current shell name reliably on Linux operating systems.
  5. cat /etc/shells – List pathnames of valid login shells currently installed
  6. grep «^$USER» /etc/passwd – Print the default shell name. The default shell runs when you open a terminal window.
  7. chsh -s /bin/ksh – Change the shell used from /bin/bash (default) to /bin/ksh for your account

Conclusion

Sometimes things are not easy as they seem, and this page is the perfect example of it. I hope you found the suggestion useful when it comes to checking your current running shell. Bash users can display shell version by typing the following command:
$ bash —version
Here is what I got from my Ubuntu Linux 20.04 LTS desktop:

Источник

Writing Shell Scripts — The Beginner’s Guide

Shell scripts are just set of commands that you write in a file and run them together. For anyone who has worked with DOS’s bat files, it’s almost the same concept. You just put a series of commands into a text file and run them together. The difference comes from the fact that bash scripts can do a lot more than batch files.

“A shell script is a computer program designed to be run by the Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text.”

Unix has more than one possible shell, and scripting any of them is a topic that can easily pack a complete book. In this post, I am going to cover the basic elements of a bash script.

Читайте также:  Windows 10 hot corner

Should I learn?

Agreed that anything you can do with a shell script, you can do that using some programming language such as Ruby, Python or Go but mostly for the small tasks, you will find yourself using Shell Scripts in one way or another.

Shell scripts are used to automate administrative tasks, encapsulate complex configuration details and get at the full power of the operating system. The ability to combine commands allows you to create new commands, thereby adding value to your operating system. Furthermore, combining a shell with graphical desktop environment allows you to get the best of both worlds

  • Automate your daily tasks
  • Create your own commands with optionally accepting input from the user
  • Portability, executing the same script in your mac and your Linux based systems.

Writing Shell Scripts

Let’s start by a Hello World example. Open your favorite editor and write a shell script file named as my_script.sh containing following lines

The first line called a hashbang or shebang. It tells Unix that this script should be run through the /bin/bash shell. Second line is just the echo statement, which prints the words after it to the terminal.

After saving the above file, we need to give it execute permission to make it runnable. You can set the execute permission as follows

Execute script as anyone of the following commands

Now we are done with the very basic shell script that prints ` Hello world` to the screen.

Before we go any deeper into few language constructs of shell scripting, you should have some basic knowledge of Linux commands . You can find several articles on the internet for that. Here is a sample article showing some of the commonly used ones.

Going Deep

Now that we have seen how to write a basic Hello World example, let’s look at some of the language constructs that you will find yourself using most of the time when writing shell scripts.

Variables

To process data, data must be kept in the computer’s memory. Memory is divided into small locations, and each location had a unique number called memory address, which is used to hold data.

Programmers can give a unique name to this memory address called variables. Variables are a named storage location that may take different values, but only one at a time.

In Linux Shell Scripting, there are two types of variable:

  • System variables — Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS.
  • User-defined variables — Created and maintained by the user. This type of variable defined in lower letters.

System variables can be used in the script to show any information these variables are holding. Like few important System variables are:

  • BASH — Holds our shell name
  • BASH_VERSION — Holds our shell version name
  • HOME — Holds home directory path
  • OSTYPE — Holds OS type
  • USERNAME – Holds username who is currently logged in to the machine

NOTE — Some of the above system variables may have a different value in a different environment.

User-defined variables are as simple as we have in any other programming language but variables can store any type of data, as in the following example:

To access user-defined variables use the following syntax:

Print to screen:

Use the above variable in a string:

Quotes

Following are the three types of quotes available in Shell scripting.

Double Quotes (“) : Anything inside double quotes will be string except \ and $. See example

Single quotes (‘) : Anything inside single quotes will be a string. See example:

Left Quotes (`): Anything enclosed in left quotes will be treated as an executable command. See examples

Conditions [if/else]

Shell scripts use fairly standard syntax for if statements. The conditional statement is executed using either the test command or the [ command.

In its most basic form an if statement is:

Have you noticed that fi is just if spelled backward? See below example that includes an else statement

Adding an else-if statement structure is used with the elif command.

There are many different ways in which conditional statements can be used in Shell scripting. Following tables elaborates on how to add some important comparison:

So this is the basic use of conditions in shell scripting is explained.

Looping

Almost all languages have the concept of loops, If we want to repeat a task ten times, we don’t want to have to type in the code ten times, with maybe a slight change each time.
As a result, we have for and while loops in the shell scripting. This is somewhat fewer features than other languages.

Читайте также:  Universal windows adb driver windows 10

The above for loop first creates variable i and assign a number to it from the list of number from 1 to 5, The shell executes echo statement for each assignment of i and on every iteration, it will echo the statement as shown in the output. This process will continue until the last item.

While loop will execute until the condition is true. See below example:

The above script first creates a variable i with the value 1. And then the loop will iterate until the value of i is less than equals to 5. The statement

i=`expr $i + 1` is responsible for the increment of value of i.

If this statement is removed the above said loop will be an infinite loop.

Functions

Function is a type of procedure or routine. Functions encapsulate a task (they combine many instructions into a single line of code). Most programming languages provide many built-in functions, that would otherwise require many steps to accomplish, for example calculating the square of a number.

In shell scripting, we can define functions in two manners.

  1. Creating a function inside the same script file to use.
  2. Create a separate file i.e. library.shwith all useful functions.

See below example to define and use a function in shell scripting:

Exit Status

The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script’s parent process.

Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.

When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the last command executed in the script (previous to the exit).

The equivalent of a exit is exit $? or even just omitting the exit.

$? is a special variable in shell that reads the exit status of the last command executed. After a function returns, $? gives the exit status of the last command executed in the function.

And with that, this article comes to an end. I hope you have got the basic idea by now. If you have any questions or feedback, leave them in the comments section below. For more information, check out Awesome Shell and GNU’s official bash reference.

Источник

13. Functions

There could be some confusion about whether to call shell functions procedures or functions; the definition of a function is traditionally that it returns a single value, and does not output anything. A procedure, on the other hand, does not return a value, but may produce output. A shell function may do neither, either or both. It is generally accepted that in shell scripts they are called functions.

A function may return a value in one of four different ways:

  • Change the state of a variable or variables
  • Use the exit command to end the shell script
  • Use the return command to end the function, and return the supplied value to the calling section of the shell script
  • echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught

This is rather like C, in that exit stops the program, and return returns control to the caller. The difference is that a shell function cannot change its parameters, though it can change global parameters.

A simple script using a function would look like this:

Line 4 identifies itself as a function declaration by ending in (). This is followed by < , and everything following to the matching >is taken to be the code of that function.
This code is not executed until the function is called. Functions are read in, but basically ignored until they are actually called.

Note that for this example the useradd and passwd commands have been prefixed with echo — this is a useful debugging technique to check that the right commands would be executed. It also means that you can run the script without being root or adding dodgy user accounts to your system!

We have been used to the idea that a shell script is executed sequentially. This is not so with functions.
In this case, the function add_a_user is read in and checked for syntax, but not executed until it is explicitly called. This is where the Shellshock bug of 2014 comes into play. Other commands after the function definition were executed, even though they were not part of the function itself. See http://steve-parker.org/articles/shellshock/ for more information on this.
Execution starts with the echo statement «Start of script. «. The next line, add_a_user bob letmein Bob Holness is recognised as a function call so the add_a_user function is entered and starts executing with certain additions to the environment:

Читайте также:  Github client mac os

So within that function, $1 is set to bob , regardless of what $1 may be set to outside of the function.
So if we want to refer to the «original» $1 inside the function, we have to assign a name to it — such as: A=$1 before we call the function. Then, within the function, we can refer to $A .
We use the shift command again to get the $3 and onwards parameters into $@ . The function then adds the user and sets their password. It echo es a comment to that effect, and returns control to the next line of the main code.

Scope of Variables

Programmers used to other languages may be surprised at the scope rules for shell functions. Basically, there is no scoping, other than the parameters ( $1 , $2 , $@ , etc).
Taking the following simple code segment:

The script, when called as scope.sh a b c , gives the following output:

The $@ parameters are changed within the function to reflect how the function was called. The variable x , however, is effectively a global variable — myfunc changed it, and that change is still effective when control returns to the main script.

A function will be called in a sub-shell if its output is piped somewhere else — that is, » myfunc 1 2 3 | tee out.log » will still say «x is 1″ the second time around. This is because a new shell process is called to pipe myfunc() . This can make debugging very frustrating; Astrid had a script which suddenly failed when the » | tee » was added, and it is not immediately obvious why this must be. The tee has to be started up before the function to the left of the pipe; with the simple example of » ls | grep foo «, then grep has to be started first, with its stdin then tied to the stdout of ls once ls starts. In the shell script, the shell has already been started before we even knew we were going to pipe through tee , so the operating system has to start tee , then start a new shell to call myfunc() . This is frustrating, but well worth being aware of.

Functions cannot change the values they have been called with, either — this must be done by changing the variables themselves, not the parameters as passed to the script.
An example shows this more clearly:

This rather cynical function changes $a, so the message «Hello World» becomes «Goodbye Cruel World».

Recursion

Functions can be recursive — here’s a simple example of a factorial function:

As promised, we will now briefly discuss using libraries between shell scripts. These can also be used to define common variables, as we shall see.

Here we see two user shell scripts, function2.sh and function3.sh , each sourceing the common library file common.lib , and using variables and functions declared in that file.
This is nothing too earth-shattering, just an example of how code reuse can be done in shell programming.

Return Codes

For details about exit codes, see the Exit Codes part of the Hints and Tips section of the tutorial. For now, though we shall briefly look at the return call.

This script checks the two external calls it makes ( useradd and passwd ), and lets the user know if they fail. The function then defines a return code of 1 to indicate any problem with useradd , and 2 to indicate any problem with passwd . That way, the calling script knows where the problem lay.

For a long time, this tutorial checked «$?» both times, rather than setting ADDUSER_RETURN_CODE=$? , and then looking at the value of ADDUSER_RETURN_CODE each time. This was a bug (thanks to Elyza for pointing it out). You have to save $? , because as soon as you run another command, such as if , its value will be replaced. That is why we save the adduser return value in the $ADDUSER_RETURN_CODE variable, before acting on its content. $ADDUSER_RETURN_CODE is certain to remain the same; $? will change with every command that is executed.

Books and eBooks

My Shell Scripting books, available in Paperback and eBook formats.

Buy this tutorial as a PDF for only $5 $1!


Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion.

Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script.

Contact

You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don’t forget to include the simple addition question at the end of the form, to prove that you are a real person!

You can buy the content of this Shell Scripting Tutorial as a PDF!

Источник

Оцените статью