I'm happy to announce the updated 2nd Edition of my free eBook — Linux Hacks. There are total of hacks in this book that will help. I'm happy to announce the release of the 2nd Edition of my Linux Hacks eBook. This eBook This free eBook contains 12 chapters with total of pages. Linux Hacks Hack Find Command. .. There are total of hacks in this book that will help you build a strong.

Linux 101 Hacks 2nd Edition Ebook Link

Language:English, Portuguese, Arabic
Country:South Sudan
Genre:Health & Fitness
Published (Last):16.04.2016
ePub File Size:22.42 MB
PDF File Size:20.65 MB
Distribution:Free* [*Registration Required]
Uploaded by: TIMIKA

All the hacks in this book are explained with appropriate Linux command examples Publisher: (); eBook Online, and PDF download. There are total of hacks in this book that will help you build a strong Apart from this Linux Hacks eBook, I've also published the following Following are the three navigation which can be done in relation to text. Linux Hacks by Ramesh Natarajan - free book at E-Books Directory. You can download the book or read it online. It is made freely available by its author.

This displays the default "? This displays the modified "Select a day PS4 Prompt used by set -x to prefix tracing output The PS4 shell variable defines the prompt that gets displayed when you execute a shell script in debug mode as shown below. The PS4 defined below in the ps4. PS4 demo script.. For Interactive Bash Shell The following is the sequence of execution of bash startup files, when you login through Bash interactive login shell: If you are a system administrator, and would like to add some global environment variable setting for all the users, you can create a shell script called env.

Add them if not. Test the Sequence of Execution One of the ways to test the sequence of execution is by adding different PS1 values to these files, then logging in again to the shell to see which PS1 value got picked up by the Linux prompt. Earlier we discussed how to use PS1 to make your Linux prompt both functional and stylish. Re-login to see the prompt change as shown below. Rename the. Executing bash at the command prompt will give another non-login shell, which will invoke.

Three Types of Bash Parameters Bash has the following three types of parameters. Variables These are created by the user either in the command-line or from a shell script to store values string, integer, etc. Special parameters These are pre-defined by bash and cannot be changed by the user, i. Positional parameter These are the arguments given to your shell scripts when it is invoked.

Variable Basics Following are the key points to remember about bash variables. Since there is not a command called "ramesh", it displays "command not found". The following will not work. Since there is no such variable, nothing will be displayed. However, the following will work. There is lot more to parameter substitution, which we'll cover in later hacks. If you quote, it is considered as one word.

If you don't quote, it will be split into multiple words. As you see below, the values will not be quoted, when it is used. As you see below, the values will be quoted, when it is used.

It is treated as a single word and displayed in one line. Bash shell does not care about the type of variables. Variables do not have to be declared. But, when you access the variable which is not used so far, you will not get any warning or error message. Instead, it will display a blank value as shown below.

When the value contains space in them, use double quotes around the value. More on quoting later.

The Geek Stuff. Executing this shell script displays a blank value, even though we assigned a value to the VAR1 from the command line. The answer is: During the execution of variable. So the variable VAR1 will not have the value in the spawned shell. You need to export the variable for it to be inherited by another program including a shell script, as shown below.

They are different variables. Positional Parameters - Shell Script Arguments Arguments that are passed to the shell scripts can be referenced as positional parameters.

CA Second Parameter: NY Third Parameter: UT All Parameters: They are special parameters. We'll discuss more about special parameters in the later hack.

For ". For debugging purposes, if you want to display all the parameters, use the following single line code-snippet. In this, x is the first character of the IFS variable. The following example shows this difference. This is optional. The Shift command moves the arguments positional parameters to the left by n positions. If you don't specify n, the arguments will be moved by 1. After 'shift 2', arguments "one" and "two" are ignored".

You cannot pass a negative number to shift; once you have shifted you cannot shift back. For example, "shift -2" will display the following error:.

When you are trying to shift more than the total number of arguments, the return status will be 1. In the above example "shift 2" return status is 0. However, if you try to do 'shift 5', the return status will be 1.

Bash Special Parameters The following table explains various bash special parameters. Special Description Parameter. Contains all the positional parameters. Contains the PID of the most recently executed background process. Contains the exit status of the most recently executed command. At the shell startup, it gives the absolute filename of the shell script being executed. Use this at the beginning of a shell script to make sure users are passing the required arguments to the shell script, and display a usage message when they don't provide the required number of arguments.

Instead of creating tmp. This is helpful, when you want to create a temporary file or directory that needs to be unique when the shell script is executed multiple times simultaneously. After executing the shell script, you'll see the temporary file and directory:. If you create a temporary file or directory inside a shell script that is needed only within the shell script, make sure to delete it at the end of the shell script:.

Previous command execution failed! First, let us take the simple example of not quoting. Both the following examples produce the same output, as multiple spaces between arguments are treated as just one single space. When you want to preserve spaces inside a string, you should double quote it, as shown below.

Basically double quotes keeps the text intact and do not allow bash to split the text at spaces and treat it as multiple arguments. Variable assignment When you are assigning a value to a variable, it is good practice to always double quote the value on the right hand side.

The following are exactly the same, as the value on the right is just a single word. But still use quotes; it is a good habit to develop. However, single quotes will not expand variable values, i.

Basically single quotes keeps the text intact, do not allow bash to split the text into multiple arguments, and do not allow variable substitution. All the special characters are treated as literal values. The backslash can be used to escape a special character in order to ignore its meaning even without using either double quotes or single quotes.

The above works the same as the following versions which use double quotes and single quotes. Variable Declaration using Declare Note: Both typeset and declare builtins are the same, but use declare.

Typeset is deprecated and is available only for backward compatibility. For normal situations, you don't need to declare a variable type to use it.

However, bash lets you declare integer, read only, array, associative array, and export type variables. The following will work whether or not you declare the variable as integer. When you declare a variable as integer, you cannot use that variable to store other types of values. For example, you cannot store a string value to a variable that is declared as integer. The undeclared variable total can be used to store either number or string:.

The following example gives an error message when you try to store a string value to an integer variable. Some string value: Use this when you want to assign a value to a variable that should not be allowed to change. A value is assigned in the same declare statement.

Once you define a read-only variable, you cannot change its value, as bash will throw an error message:. For example, if you define a variable in the command line it will not be available to a shell script executed from the command line, as the shell script spawns a new bash to execute the script. In the following example, a variable global is defined in the command line. If you spawn a new bash shell, the value of the global variable is not defined. When you go back to the parent shell, you can again see the global variable.

To export a variable to a subshell or child process, use declare -x. In the following example, the variable global is declared with -x. Now, when you spawn a new bash shell, the value of the global variable is still available, as it was declared using 'declare -x' in the parent shell. This is a one way process, i. The child process has its own copy of the variable. Modify the value of the global in the child process, and exit to the parent process to check the value. When the declare command is used without any arguments, it will display both the environment variables and user defined local variables.

From the command line, you can perform arithmetic without the let command. However, this sequence would not work properly in a shell script, as shown in the next example. Therefore, inside a shell script you should use the let command. Also shown in the example is the use of let to do multiple arithmetic expressions on one line. Both of the following will give the same result.

This is very much like let. Both of the following examples work exactly the same. Spaces in the let command would separate the line into multiple expressions:. Since supports spaces, you cannot use multiple expressions on one line:. Let or or expr -- which one to use?

All of the following are the same:. In general, use either let or. Avoid the expr command because it is really calling a unix command to evaluate the arithmetic expression; that means it will unnecessarily spawn a new process.

Here is a sample shell script that demonstrates various arithmetic operators:. Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings. This restriction applies even if you use let, , or expr. Operator Precedence Bash evaluates an expression in a particular order based on the precedence of the operators. The following table lists highest precedence operators first. To be completely safe, use parentheses to control the order of evaluation!

Ternary operator expr. Number Comparison Before we start discussing if conditions, for loops, and while loops, let us understand what operators we can use for numeric and string comparisons in the [ ] and test command of a if statement.

The following example shows how to use the number comparison operators in an if statement. Execute the above shell script by passing an argument as shown below to see how the various test conditions work:. String Comparison To compare strings use the following operators. Is the given string empty? Is the given string not empty? The following example shows how to use the string comparison operators in an if statement.

Execute the above shell script by passing an argument to see how the various test conditions work:. Please note: Both do string comparison inside the if []; test construct. Additional notes on string comparison and the example -n and -z need to be added before the variable to be tested. Otherwise bash wont have anything to test. While using -z, we are really checking whether the given variable is either zero-byte or not null.

The variable city was never defined anywhere before. So, when you use -z to check whether it is null, the test will return true.

The following example starts apache only if it is not already running. When you are referencing a variable, you should always double quote it to avoid any errors. This will not give any error when the city doesn't contain any space in it as shown below.

However when you have space in the value of the variable city, this will fail and throw an error message as shown below. In the following syntax, statement1 is executed and if the output is true, bash will execute statements 2 and 3. In most cases, statement 1 will be a conditional expression in brackets, also called the [ command; this is called a simple if statement. If the conditional expression is true nonzero , bash executes the statements enclosed between the keywords then and fi, otherwise the statement list is skipped.

The keyword "then" should be in a separate line. You can use the keyword then in the same line as "if" by adding a semicolon as shown below:. The keyword test may be used instead of brackets. Syntax using test command:. The following example shows the three variations of the simple if statement. If the conditional expression is true, bash executes the statements 1 and 2. If the conditional expression is false, it executes statements 3 and 4. In either case, execution resumes with the subsequent statements.

This example shows the usage of the if-then-else-fi statement:. This construct allows you to to select one of many blocks of code to execute by testing two or more conditional expressions. If-elif-else Syntax:. If conditional expression1 is true, bash executes statements 1 and 2. Otherwise, if conditional expression2 is true, it executes statements 3 and 4. Otherwise, it executes statement 5. You can use as many elif blocks as you need, but remember that the expressions will be tested in order from top to bottom so it will take longer to get to the final else block.

In time critical applications this can be important. The following example shows the usage of the if-elif-else-fi statement. This is essentially identical to using elif, but with an important difference: Arithmetic Expressions in an if Statement You have to be very careful when you are evaluating arithmetic expressions in the conditional part of your if statement. For the shell, you already know the following exit status: However inside an if statement, when an arithmetic expression's result is 0, it is considered false, and when an arithmetic expression's result is anything except 0, it is considered true.

File Test Operators in If Condition In Linux everything is treated as a file, including the directory, a block device, a character device, or a traditional regular file. So, all the tests below are called file test operators.

In all the explanations below, "regular file" has a special meaning: The word "file" mentioned by itself could be any types of file directories, block devices, regular files, etc.

File Test Description Operator.

You can reverse the meaning of any of the above conditions by adding a! Check if the file exists As we explained above, file could be anything. So, all of the following will return true. Check Whether a Specific File Type Exists You might want to know whether a specific directory, or link, or block device exists.

Use the appropriate file test condition as shown in the next example below for this testing. For most file exists scenarios, you'll be testing whether a directory exists, or a regular file exists. Instead of using -e, I always prefer to specify the exact type of the file that I'm looking for, with d or f or b or h.

Check for Permissions -r, -w, and -x check whether you have read, write, and execute permission, respectively, on the specified file or directory:.

Try the permission testing example from both root and non-root accounts to see different levels of access. Reverse Test Conditions with! You can reverse the meaning of any test condition by using! For example, -s checks whether the file is not empty.

If you want to check whether the file empty, use! You can evaluate multiple expressions using -a or o. AND Comparison using -a -a does and comparison inside a conditional expression. Expressions can be either number comparison or string comparison. The following example demonstrates and numeric comparison:. California capital is sacramento. California capital is not los angeles. OR Comparison using -o -o does or comparison inside a conditional expression.

The above example uses string comparison but o can be used with numeric expressions, just like a. We demonstrated the use of! If command1 executes successfully with a return status of 0 , bash moves on and executes command2. If command1 fails with a return status of non zero , bash doesn't execute command2 or command3 or anything else on that line. If command2 executes successfully, bash executes command3.

However, the second command failed because we've given space before and after the equal sign in variable assignment. Since command2 failed, command3 and 4 and 5 never got executed. The return status of the whole list is exactly the same as the exit status of the last command in the list that failed. When all the commands execute successfully, you can further execute one or more commands in the if command body. But if we had more commands in the body of the if statement the form shown previously would be best.

To summarize: Each command in the or list. If command1 executes successfully return status of 0 , bash doesn't execute command2 or command3. If command1 fails return status of non zero , it executes command2. If command2 executes successfully, bash doesn't execute command3. The following example has 5 commands separated by. However, since command 1 got executed successfully, the rest of the commands in this list will never be executed.

One good use for the OR list is to replace a simple if! Another use of is to exit a shell script with appropriate status when a necessary operation fails, as shown below. Tilde expansion, arithmetic expansion, and parameter expansion. Good Morning, Mr. Hero" fi 3. Bond [[test]] command: Hero [[test]] command: Bash For Loops Cycle through a List of values For loops allow repeated execution of a command sequence based on an iteration variable.

Bash supports two kinds of for loop, a list of values and a traditional c-like method that we discuss in a later section. If list is missing from the for statement, then bash uses positional parameters that were passed into the shell.

In this form, bash executes the command s enclosed in the body between do and done once for each item in the list. If the list contains 5 items, the for loop will be executed a total of 5 times. Each time through, the current item from the list will be stored in variable varname before the body executes. So, this varname can be processed in the body of the loop. The following several examples show how to use the bash for loop list of values method. Mon Weekday 2: Tue Weekday 3: Wed Weekday 4: Thu Weekday 5: The list of values should not be separated by comma Wrong: Mon, Tue, Wed, Thu, Fri.

The comma will be treated as part of the value, i. Mon, Weekday 2: Tue, Weekday 3: Wed, Weekday 4: Thu, Weekday 5: The list of values should not be enclosed in quotes.

If you enclose in double quotes, it will be treated as a single value instead of 5 different values , as shown below. Mon Tue Wed Thu Fri. Using a Variable as List Instead of providing the values directly in the for loop, you can store the values in a variable, and use the variable in the for loop after the "in" keyword, as shown in the following example. As a best practice, you should always quote bash variables when you are referring to them, except in special cases.

This is one of the special cases. Lots of people fall into this trap! Be careful and do not double quote your variables in for loops. Get List Values from Positional Parameters If you don't specify the keyword "in" followed by a list of values in the bash for loop, it will use the positional parameters passed to the shell script:.

You should not include the keyword "in" when specifying the for loop, because bash would look see an empty list and never execute the loop. Heres an example:.

Looping Through Files and Directories You can loop through the files and directories under a specific directory with a for loop. For example, the following will display all the files and directories under your home directory. This is the concept that is used in the above for5. The same argument that is used for an ls command can be used in a bash for loop, as shown in the example below.

File 2: Continue a Bash For Loop Under certain conditions, you can ignore the rest of the commands in the body of a for loop, and continue the loop from the top again using the next value in the list , using the continue command as shown below. Mon weekday Day 2: Tue weekday Day 3: Wed weekday Day 4: Thu weekday Day 5: Fri weekday Day 6: You may have noticed that an else statement containing the second echo would have worked too.

There are usually many ways to do the same thing. Range of numbers using "in" You can loop through a range of numbers in the for loop by using brace expansion after the in keyword. Range of Numbers With Increment using "in".. The following example loops through a set of numbers but each time through the loop variable is incremented by two instead of one. The loop will execute five times because the loop variable will be out of range after that.

Bash for loops using C like syntax The second form of bash for loop is similar to the C programming language for loop, which has three expressions initialization, condition and update. Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop.

All the statements between do and done are executed repeatedly as long as the value of expr2 is TRUE. After each loop iteration, expr3 is evaluated.

This is usually used to increment a loop counter. Loop using C-Style Generate and display 5 random numbers using the bash C-style for loop:. Infinite Loop Using Bash For When you don't provide the start, condition, and increment in a C-style for loop, it will execute forever. You need to press Ctrl-C to stop the loop. Dont forget you will need to press Ctrl-C to break from this example:.

Increment Two Values Using Comma in C-style for loop In the bash c-style loop, in addition to incrementing the value that is used in the condition, you can also increment some other value or perform some other action. In both the initialization section and the increment section of the C-style for loop, you can use multiple statements separated with a comma.

This example uses i for control and manipulates j separately:. While Loop Another iteration statement offered by the bash shell is the while statement.

Expression is any expression which returns a scalar value. Commands between do and done are executed while the provided conditional expression is true. This example reads data from stdin the keyboard and writes it into a file. EOF Ctrl-Z is needed to terminate the input:.

In this example the parts you type are in bold. Ctrl-z means you type control z to terminate input. In the previous example, bash reads the filename from the user, and then reads lines of data from stdin until it sees EOF, appending each line to the file specified by filename.

Bash redirection of the echo command output is used to append the lines. EOF terminates the loop because the read fails i.

The next example has bash write data from a file to stdout similar to cat.

The input is still taken from stdin in this example, but bash redirection is used so that stdin comes from the specified file rather than from the keyboard.

Note how both of these examples have made use of the very powerful technique of redirection that we discuss more in a later section. In this example, bash gets the filename to read from stdin the keyboard and then uses exec to redirects stdin, getting further input from a file instead of the keyboard. As in the previous example, the read command fails when EOF occurs, terminating the loop. Infinite Loop Using Bash While You can use while true to create an infinite loop, just like the for ;; syntax demonstrated earlier.

The next example uses an infinite loop to test whether a server is up and running. The sleep command is used to do the ping test at a periodic interval in this case sixty seconds. In this way. Test the server with ip-address Until Loop The bash until loop is very similar in syntax and function to the while loop.

The only difference between the two is that the until statement executes its code block while its conditional expression is false, and the while statement executes its code block while its conditional expression is true. This bash until loop example monitors the size of the logfile.

Once the logfile size reaches bytes, it makes a copy of that logfile. The following bash until example is used to wait till a remote machine comes up before connecting via ssh to that machine. The until loop ends only when the ping succeeds returns 0. The bash until loop is quite useful at the command line as a way of waiting for certain events to occur. If the value of the "var" matches "pattern1", it will execute command1, command2, and any other commands in the "pattern1" block.

If the value of the "var" matches "pattern2", it will execute command3, command4, and any other commands in the "pattern2" block.

The case statement ends with "esac", which is nothing but the reverse of the word case. Each set of commands should end with two semi-colons ;;. This simple case example sets variables state and capital based on the argument given on the command line which should be the state abbreviation for either California or Nevada. In the above example, when the value of stateabbr is "CA", bash executes the two commands that are under the pattern "CA".

It skips over the other cases after that, continuing after the esac statement. Backup Log files" echo "b. Backup Config files" echo "c. Backup Home Directory" echo "d. Exit" echo "Enter your choice: In the above example, the "pattern" doesn't just contain one value. It has multiple values. For example "a A ", indicates that irrespective of whether users enters a or A, the commands in this pattern will be executed.

When you get to this point, it means that none of the patterns until this point is matched. So, this should be an invalid value entered by the user. The following table explains the three case terminators. Case Description Terminator. Case Statement Example using ;; In the example below, the other cases are skipped; only the CA case is executed.

But since ;; is used to terminate the NV block, the rest of the cases after NV are skipped.

Linux 101 Hacks 2nd edition eBook Download

There are some problems with the above script: Once you make a selection, it keeps looping, and doesn't exit. You have to press Ctrl-C to exit the loop. The prompt displays the ugly "? The environment variable PS3 is used to set the display prompt for case statements. When you have a menu item that contains spaces in it, you should use double quotes to enclose the individual items in the list of values.

In the following example, if you don't enclose "New York" in double quotes, New and York will be treated as two separate menu items, not what we want. Instead of giving the list of values directly after the "in" keyword, you can also use a variable that contains the list, as shown in the example below.

Make sure you don't enclose the variable that you specify after the "in" keyword in double quotes, as the value will be treated as single word. You can also omit the keyword "in" and the list of values. In that case, the select command will use the positional parameters as list of values as shown in the example below. Additional Bash Built-in Commands Bash builtins are commands that are built as part of bash itself. Certain builtins are available only in bash and are not available in other shells or as an external command.

However, some bash builtins replicate an existing shell commands. List of bash builtins The following table contains list of available shell builtins. Some of them are explained in separate hack with examples. To know more about a specific builtin use the help builtin command. For example, "help test" will give you information about the test builtin.

Colon is null command. It does nothing. Help Builtin Get quick help about bash builtin commands. Echo Builtin The echo builtin command supports n and e options to suppress newline or insert a special character. The following table explains some of the special character codes that you can use with e:.

To print special characters use echo e, to suppress newline use echo n. Examples are on the next page. It is very helpful to suppress newline when you have multiple echo commands inside a shell script, but you would like to see the output of those echo commands on a single line instead of each echo command printing the output on a different line.

When you use echo -e, it is treated as a tab character. Color Your echo Output You can color the text that is used in the echo statement as shown in the example below. Replace [0 with [1 in the above table for dark color. In addition to using the color codes, you can do additional text manipulation using tput. For example, bold or underline the text:. Printf Builtin Bash has a formatted print command printf. These tables have codes for the format; usage will be described on the next page.

Format Description Identifier. Format Description Modifier. In the bash printf builtin, format is a double quoted string with a mixture of literal text and format identifiers modified by format modifiers that will be replaced with the arguments following the format string:. The following example prints a string in a field that is at least 5 characters wide. When the supplied string value is less than 5 characters, bash will add leading spaces:.

When the value is more than 5 characters wide, it will print the full string:. If you want an exact fixed width, even when the printed value contains more characters, use a. You then pass the modifying number as an argument. Both of the following examples do exactly the same. Use a hyphen to pad spaces on the right side of the value instead of the default left side. This is helpful when printing a record with multiple fields.

When you use 0 along with a numeric format identifier, printf adds leading 0s to the printed numbers, instead of spaces. Print Fixed Width space before: Print Exact Width truncate characters: Print Fixed Width using argument: Print Fixed Width space after: Print Numbers: Print Fixed Width Numbers zeros before: Read Builtin The bash read command is used to get input from the user interactively or even non-interactively, from a file and store it in a variable.

You can read one value, or multiple values space, comma, or tab separated in the same read statement. When you enter multiple values, the 1st word goes to the 1st variable, 2nd word to 2nd variable, etc. When there are more values than variables, the last variable will hold the remaining words; when there are more variables than values, the additional variables will have null. Here are some of the most frequently used variations of the read command:. You said: The values that are read are assigned to the array starting from 0.

Displays the prompt before reading the value. This is easier and quicker than giving a echo statement. This doesn't echo the value as you enter. This is useful for reading any sensitive information from the user. If the user doesn't enter anything, read waits for 10 seconds and times out. The read command returns after you've entered exactly 5 characters, no matter how many variables are being assigned.

When you try to enter more than 5, read will not accept them; it will automatically stop at the 5th character input, and continue with the rest of the shell script logic. Getopts Builtin Use getopts in a shell script to get command line options typed when calling the script.

You can pass options with or without any arguments.

File Details

Please note that getopt is not the same as getopts. However, the getopts builtin is functionally similar to the getopt external program.

Here is a simple usage example of passing options to a shell script: In the above example, there are 4 options c, v, f and z. Option names have to be only a single character. Option f also has an argument: You can combine multiple options together. For example, the c, v, and z options can be combined as cvf as shown below. For the above example, the optionstring would be "cvf: The colon after option f indicates that option f will have an argument.

For getopts to work properly, each single character option passed to the script should have - as the prefix. When bash it encounters an argument that doesn't have hyphen as a prefix, it will terminate getopts parsing immediately.

Typically you would use getopts along with while and case statements as shown in the example below. In the following example, the 2nd option "v" is given without the hyphen. So, getopts processes only the 1st option -c and stops. The first colon in the optionstring is optional. In the above example, you can also specify the optionstring as shown below.

27 Best Linux Tutorial Books That You Need To Download Now

But, when you pass an argument to the script that doesn't exist in the optionstring, it will throw error message.

So, using a colon in front will not display that error message. Hash Builtin The bash shell has a hash table where the commands you execute are stored. The full path is included in the hash table. When you execute the same command next time, bash won't search the PATH variable, instead it will pick up the command from the hash table and run it.

This is demonstrated in the sequence of examples shown below. The hash command without any argument displays the content of the hash table. In this example, it is empty, as we just started the session. Now the hash command will display the hash table that contains two fields: Total number of hits for the command 2. The command itself with the full path.

Next time when you execute the ls command, bash will not search the PATH variable, it will just pick up the full-path of the command from the hash table and execute it. View the hash table again. You'll still see two entries, but the ls command hits counter will show 3, as we executed ls 3 times so far in this session.

You can also add a command to the hash table without executing it. The following will add the tar command to the hash table. Since the tar command was added to the hash table without executing it, the hits will be 0 for the tar command as shown below. The one option that is useful is pwd -P, which prints the real directory structure without symbolic links. Now, use the symbolic link to cd to that directory, and do a pwd.

This will show only the symbolic link directory that you used to cd into it. If you really want to know the original directory where you are currently located, you should use pwd -P, as shown below. You can create a function called mypwd and add it to the. Now, let us assume that you want to override the default pwd, and call your custom function anytime you execute pwd. Of course you can rename the mypwd function in your. If you rename the custom mypwd function to pwd, then when you execute the pwd command, it will go into an infinite loop because it is calling itself.

So, when you are referring to a bash builtin from a custom function that has the same name as the builtin, you should explicitly call the original bash builtin using the "builtin" command. By default all the builtins are enabled. For example, when you type alias, it will execute the alias builtin and display the output. To disable the bash alias builtin, use enable with the -n option. Once you disable a builtin, when you try to execute it, bash will display command not found as shown below.

To view all the enabled shell builtins, execute 'enable -p'. Type Builtin A command that you execute from the command line can be an alias, a shell builtin, a shell keyword, or an external program. Use the type command to identify the type of a particular command.

The following example shows that ls is an alias, pwd is a builtin, if is a shell keyword, and file is an external program. If a command is available both as builtin and external program, and you would like to view both, you can use "type -a" as shown below. Ulimit Builtin Using ulimit you can control the amount of resources that can be assigned to processes that are started by the bash shell. To view all the current limits, use ulimit -a, as shown below. From this output, you can see that the total number of "open files" allowed for a process that is created by the shell is , the "max memory size" available for a process that is created by the shell is "unlimited", etc.

You can view a specific resource using the short option for that resource. The short option for a particular resource is displayed in the above ulimit -a output within. For example, the short option for open files is n:. To change the value of a specific resource, specify the new value as an argument to the ulimit command. The following example changes the number of "open files" from the default to Use S or H to an option to display the soft or Hard limit, respectively.

You can use the directory stack to save and restore your current working directory by pushing and popping, respectively. Display the directory stack pushd: Push directory onto the stack popd: Pop directory from the stack and cd to it. Dirs will always print the current directory followed by the content of the stack. Even when the directory stack is empty, the dirs command will still print the current directory. How to use pushd and popd? Let us first create some temporary directories.

Push these temporary directories onto the directory stack as shown below. After pushing the above 4 directories to the stack, let us view the content of the directory stack using the dirs command. At this stage, the directory stack contains the following directories: The last directory that was pushed to the stack will be at the top. When you perform popd, bash will cd to the top directory entry in the stack and remove it from the stack.

After the above popd, the directory stack contains the following directories:. Now, do a popd to get pop another directory from the stack and switch to it.

Now, do another popd to get pop a directory from the stack and switch to it. Dirs By default, dirs command prints the content of the directory stack in a single line as shown below. Use dirs -p to print all the entries in the directory stack in a separate line:. Use dirs -v to print all the entries in the directory stack, each on a separate line along with its position in the stack:. For example, to display the 3rd element, do the following:. Use dirs -n to display the nth element counted in reverse order from the directory stack.

For example, to display the 3rd element from the bottom, do the following:. Using the pushd -n option, you can add the directory to the stack without switching to it. Push home directory onto the stack but dont change your working directory:. Using pushd -2, you can rotate the stack downward, making the 2nd element from the end of the list the new top of the stack.

Popd By default when you execute the popd command, bash will pick the top entry from the directory stack, cd to it, and delete that entry from the stack. Let us assume the directory stack contains the following items, and the current directory is the home directory.

Using popd -n, you can delete the top entry from the stack without switching to that directory. Bash will not switch to that directory. Please note that when you use -, the last item is counted as 0.

Shopt Builtin shopt stands for shell options.

To view all the shell options and their current status whether the option is enabled or disabled , do the following:. To view the current status of a specific shell option for example, cdspell , do the following:. This is helpful when you want to take the shell options from one system replicate them on some other system.

Just copy the output of shopt -p on one system, and paste it in to the other system, or redirect the shopt p output to a file that you execute on the other system. Some shopt options can also be controlled using the set builtin command. The following table displays all shopt options and what they mean. By default, all of these options are off except those that are in bold.

Use only the directory name to cd to a autocd directory. Minor spelling mistakes are corrected cdspell automatically. When jobs are running, first exit checkjobs command will list all running jobs, second exit command will exit the shell. Multiple line command are stored in the cmdhist same history entry.

Minor spelling corrections will be dirspell performed for directory name for glob matching. Format a partition using mke2fsk Hack Mount the partition Hack Fine tune the partition using tune2fs Hack Create a swap file system.

Create a new user Hack Create a new group and assign to an user Hack Use ssh-copy-id along with ssh-agent Hack Crontab Hack Pass different httpd. Use a temporary DocumentRoot without modifying httpd. Increase the Log Level temporarily Hack Display the modules inside Apache Hack Show all accepted directives inside httpd.

Validate the httpd. Display the httpd build parameters Hack Load a specific module only on demand Chapter Bash Scripting Hack Execution Sequence of. How to generate random number in bash shell Hack Debug a shell script Hack Quoting Hack Free command.Add the following line to the. But why people do know?

The name of the array refers to the 1st element of the array, i. When you want to truncate your log files, don't do rm and touch, which might mess-up the file permission. Read data file fields inside a shell script Chapter Colon is null command.

The environment variable PS3 is used to set the display prompt for case statements. Download Free eBook Enter your email address below to download the Linux Hacks 2nd edition eBook immediately and sign-up for our monthly newsletter. This is the default mode. Command Execution Sequence

WADE from Oakland
Review my other posts. I enjoy yubi lakpi. I am fond of reading novels politely .