shell – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Mon, 09 Jan 2023 02:23:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 10 Most Popular Open Source Linux Shells https://tecadmin.net/most-popular-open-source-linux-shells/ https://tecadmin.net/most-popular-open-source-linux-shells/#respond Mon, 09 Jan 2023 02:23:29 +0000 https://tecadmin.net/?p=33682 The Linux shell is a command-line interface that allows users to interact with the operating system and execute commands. There are several different types of Linux shells available, each with its own set of features and characteristics. In this article, we will introduce the 10 most popular open-source Linux shells, which are widely used by [...]

The post 10 Most Popular Open Source Linux Shells appeared first on TecAdmin.

]]>
The Linux shell is a command-line interface that allows users to interact with the operating system and execute commands. There are several different types of Linux shells available, each with its own set of features and characteristics. In this article, we will introduce the 10 most popular open-source Linux shells, which are widely used by developers, system administrators, and other users around the world.

1. Bash Shell

Bash, or the Bourne Again Shell, is the default shell on most Linux and Unix-like operating systems. It is a widely-used, powerful, and flexible shell that is suitable for a wide range of tasks.

The main features and characteristics of the bash shell are:

  • Command history: Bash allows users to easily access and execute previous commands using the up and down arrow keys.
  • Job control: Bash supports job control, which allows users to run processes in the background, interrupt them, and resume them.
  • Shell scripts: Bash supports shell scripting, which allows users to automate tasks by writing scripts that execute a series of commands.
  • Aliases: Bash allows users to create aliases for frequently used commands, which can save time and improve efficiency.

2. Zsh Shell

Zsh, or the Z shell, is a feature-rich and highly customizable shell that is popular among power users. It has a large number of built-in features and supports a wide range of plugins and themes.

  • Command completion: Zsh supports programmable command completion, which allows users to customize the way command completions are displayed and triggered.
  • Plugins: Zsh supports a wide range of plugins that can add additional features and functionality to the shell.
  • Themes: Zsh supports customizable themes that allow users to change the appearance of the shell prompt and other elements.
  • Advanced command history: Zsh includes advanced command history features, such as the ability to search and execute previous commands.

3. Fish Shell

Fish, or the Friendly Interactive Shell, is a modern and user-friendly shell that is designed to be easy to use and learn. It has a syntax highlighting the feature and supports auto-suggestions, making it popular among new users.

  • Syntax highlighting: Fish includes syntax highlighting, which makes it easier to read and understand scripts by displaying different parts of the code in different colors.
  • Auto-suggestions: Fish supports auto-suggestions, which offer suggestions for completing commands as the user types them.
  • User-friendly syntax: Fish has a user-friendly syntax that is designed to be easy to learn and use.
  • Tab completions: Fish supports tab completions for commands, options, and arguments.

4. Ksh Shell

Ksh, or the Korn Shell, is a shell developed by David Korn at Bell Labs. It is known for its command history feature, which allows users to easily access and execute previous commands.

  • Command history: Ksh includes a command history feature that allows users to easily access and execute previous commands.
  • Aliases: Ksh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Functions: Ksh supports the creation of functions, which are reusable blocks of code that can be called from multiple places in a script.
  • Array variables: Ksh supports array variables, which allow users to store and manipulate multiple values in a single variable.

5. Csh Shell

Csh, or the C shell, is a shell that was developed at the University of California, Berkeley. It is similar to the C programming language and is known for its syntax and control structures.

  • Syntax and control structures: Csh is based on the C programming language, and its syntax and control structures are similar to those of C.
  • Aliases: Csh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Command history: Csh includes a command history feature that allows users to easily access and execute previous commands.
  • Job control: Csh supports job control, which allows users to run processes in the background, interrupt them, and resume them.

6. Dash Shell

Dash, or the Debian Almquist Shell, is a lightweight and fast shell that is designed to be used as the default shell on Debian-based systems. It is known for its minimalism and speed, and is often used in scripts and other automated tasks.

  • Lightweight and fast: Dash is a lightweight and fast shell that is designed to be used as the default shell on Debian-based systems.
  • Portable: Dash is portable and can be easily compiled on a wide range of systems.
  • Suitable for scripts: Dash is often used in scripts and other automated tasks due to its speed and minimalism.

7. Tcsh Shell

Tcsh, or the TENEX C shell, is a shell that is based on the C shell and includes additional features such as command line editing and programmable completion.

  • Command line editing: Tcsh includes command line editing features, such as the ability to use the left and right arrow keys to move the cursor, and the CTRL-R key to search the command history.
  • Programmable completion: Tcsh supports programmable completion, which allows users to customize the way command completions are displayed and triggered.
  • Aliases: Tcsh allows users to create aliases for frequently used commands, which can save time and improve efficiency.

8. Ash Shell

Ash, or the Almquist Shell, is a lightweight and portable shell that is often used in embedded systems and other resource-constrained environments.

  • Lightweight and portable: Ash is a lightweight and portable shell that is often used in embedded systems and other resource-constrained environments.
  • Suitable for scripts: Ash is often used in scripts and other automated tasks due to its small size and minimalism.
  • POSIX compliance: Ash is compliant with the POSIX shell specification, which makes it suitable for use in scripts that need to be portable across different systems.

9. Psh Shell

Psh, or the Public Domain Korn Shell, is a fork of the Korn shell that includes additional features and improvements. It is known for its portability and compatibility with other shells.

  • Command history: Psh includes a command history feature that allows users to easily access and execute previous commands.
  • Aliases: Psh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Functions: Psh supports the creation of functions, which are reusable blocks of code that can be called from multiple places in a script.
  • Portability: Psh is designed to be portable and can be easily compiled on a wide range of systems.

10. Xonsh Shell

Xonsh is a Python-based shell that combines the features of multiple shells and adds additional features such as syntax highlighting and tab completion. It is known for its flexibility and integration with other Python tools.

  • Python-based: Xonsh is a Python-based shell that allows users to use Python syntax and libraries in the shell.
  • Syntax highlighting: Xonsh includes syntax highlighting, which makes it easier to read and understand scripts by displaying different parts of the code in different colors.
  • Tab completions: Xonsh supports tab completions for commands, options, and arguments.
  • Integration with other tools: Xonsh can be integrated with other Python tools and libraries, allowing users to leverage their capabilities in the shell.

Wrap Up

These are some of the most popular open-source Linux shells available today. Each shell has its own set of features and characteristics, and the right shell for a specific task will depend on the needs and preferences of the user.

The post 10 Most Popular Open Source Linux Shells appeared first on TecAdmin.

]]>
https://tecadmin.net/most-popular-open-source-linux-shells/feed/ 0
Checking If a Command Succeeded in Bash Using the `$?` Special Variable https://tecadmin.net/check-if-a-command-succeeded-in-bash/ https://tecadmin.net/check-if-a-command-succeeded-in-bash/#respond Tue, 27 Dec 2022 17:17:44 +0000 https://tecadmin.net/?p=33222 In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can [...]

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can examine the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

In this article, we will explore different ways to check the exit status of a command in Bash, including using the `$?` special variable, using the `&&` and `||` operators, and using scripts and functions. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios when working with Bash.

Checking If a Command Succeeded in Bash

In Bash, you can check if a command succeeded or failed by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

For example, consider the following command:

ls -l /etc/ 

This command lists the contents of the `/etc` directory in long format. To check if this command succeeded, you can use the following code:

ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This code checks the exit status of the ls command by examining the value of the $? special variable. If the value of `$?` is `0`, the command succeeded, and the code prints “Command succeeded”. If the value of `$?` is non-zero, the command failed, and the code prints “Command failed”.

Check Exit Status of a Function

You can also use the `$?` special variable to check the exit status of a command in a script or function. For example, consider the following script:

#/usr/bin/env bash

check_command() {
    command
    if [ $? -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

check_command ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This script defines a function check_command that takes a command as an argument and checks the exit status of the command. The function returns `0` if the command succeeded and `1` if the command failed. The script then calls the check_command function with the ls command and checks the exit status of the function by examining the value of the `$?` special variable. If the value of `$?` is `0`, the command succeeded, and the script prints “Command succeeded”. If the value of `$?` is `1`, the command failed, and the script prints “Command failed”.

Check Exit Status Using `&&` And `||` in Bash

In addition to using the `$?` special variable, you can also use the `&&` and `||` operators to check the exit status of a command and execute different commands based on the result. For example, consider the following code:

ls -l /etc/ && echo "Command succeeded" || echo "Command failed"

This code checks the exit status of the `ls`‘ command and executes different commands based on the result. If the ls command succeeded, the code prints “Command succeeded”. If the ls command failed, the code prints “Command failed”.

Conclusion

In conclusion, checking if a command succeeded or failed in Bash is a useful task that can be accomplished by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of `0` indicates success, and a command with a non-zero exit status indicates failure. To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

You can also use the $? special variable to check the exit status of a command in a script or function or use the `&&` and `||` operators to check the exit status and execute different commands based on the result. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios, such as when you want to execute different commands based on the success or failure of a command or when you want to perform error handling in a script.

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
https://tecadmin.net/check-if-a-command-succeeded-in-bash/feed/ 0
How To Customize Bash Prompt (PS1) In Linux https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/ https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/#respond Wed, 21 Dec 2022 06:19:35 +0000 https://tecadmin.net/?p=22778 In Linux, PS1 is an environment variable that specifies the format of the command prompt displayed in the terminal. It stands for “Prompt String 1” and it is used to customize the appearance of the prompt. By default, the bash prompt includes the current username, hostname, and current working directory, followed by the `$` symbol [...]

The post How To Customize Bash Prompt (PS1) In Linux appeared first on TecAdmin.

]]>
In Linux, PS1 is an environment variable that specifies the format of the command prompt displayed in the terminal. It stands for “Prompt String 1” and it is used to customize the appearance of the prompt.

By default, the bash prompt includes the current username, hostname, and current working directory, followed by the `$` symbol for a regular user or the `#` symbol for the root user. The prompt is displayed on the command line, and it indicates that the terminal is ready for input.

You can customize the bash prompt by modifying the value of the PS1 variable. For example, you can use special characters and codes to change the colors, font styles, and other formatting options of the prompt. You can also include other information, such as the current time or the git branch name, in the prompt.

In this tutorial, we will discuss how to change the PS1 bash prompt and make is colorful in Linux.

Change Bash Prompt (PS1) in Linux

To customize the bash prompt (PS1) in Linux, you can use the following steps:

  • Open the `~/.bashrc` file in a text editor. This file is located in your home directory and contains configuration settings for the bash shell.
  • Find the line that sets the value of `PS1`. It will look something like this:

    PS1='[\u@\h \W]\$ '

    Check the below screenshot:

    How to Change PS1 Prompt in Linux

  • Modify the value of PS1 to customize the appearance of the prompt. You can use the following special characters to include information in the prompt:
    • `\u`: The username of the current user
    • `\h`: The hostname up to the first .
    • `\H`: The full hostname
    • `\w`: The current working directory
    • `\W`: The basename of the current working directory
    • `\$`: This code represents the prompt symbol, which is $ for a regular user and # for the root user.
  • For example, to customize the prompt to display the current working directory and the $ symbol, you could use the following value for PS1:

    PS1='\w \$ '

    Check the below screenshot:

    Changing PS1 Prompt in Linux

  • Save the `~/.bashrc` file and exit the text editor.
  • Run the following command to apply the changes to your current session:
    source ~/.bashrc 
    

Your bash prompt will now be customized according to the value you set for PS1.

Make Colorful Bash Prompt (PS1) in Linux

To customize the bash prompt (PS1) in Linux, you can use special characters and codes to add colors and other formatting options.

Here’s an example of a bash prompt that includes a red username, a green hostname, and a blue current working directory:

PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[0;32m\]\h\[\e[m\]@\[\e[0;34m\]\w\[\e[m\]\$ '

To set the bash prompt in your current session, you can simply copy and paste the above code into the terminal and press Enter. To make the change permanent, you can add the same line to the .bashrc file in your home directory.

How to Make Colourful PS1 Prompt in Linux

Here’s a breakdown of the different color codes used in the example above:

  • \[\e[0;31m\] – This code sets the text color to red. The 0;31 value specifies the color, with 31 representing red.
  • \[\e[0;32m\] -This code sets the text color to green. The 0;32 value specifies the color, with 32 representing green.
  • \[\e[0;34m\] -This code sets the text color to blue. The 0;34 value specifies the color, with 34 representing green.
  • \[\e[m\] – This code resets the text color to the default value. So the remaining text will be default in color.

You can use other codes to customize the bash prompt with different colors and formatting options. For example, to make the text bold, you can use \[\e[1m\] before the text and \[\e[m\] after the text. You can find a list of all the available codes in the PROMPTING section of the bash man page.

I hope this helps! Let me know if you have any questions.

The post How To Customize Bash Prompt (PS1) In Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/feed/ 0
Efficiently Reading a File Line by Line in a Shell Script https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/ https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/#respond Fri, 16 Dec 2022 10:52:21 +0000 https://tecadmin.net/?p=6390 Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods [...]

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods are more efficient than others. In this article, we’ll explore some of the most efficient ways to read a file line by line in a Linux shell script.

Using while loop

The most basic way to read a file line by line in a shell script is to use a while loop and the read command. The read command reads a line of input from the file and stores it in a variable, which can then be processed by the script. The while loop allows you to iterate through the lines of the file until the end is reached. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < file.txt

This method is simple and easy to understand, but it has some limitations. One limitation is that the read command can only read one line at a time, so it can be slower for large files with many lines. In addition, the read command can only read from standard input (stdin), so you must use the < operator to redirect the contents of the file to stdin. This can be inconvenient if you need to read from multiple files or if you want to read from a file that is not in the current directory.

Using while loop with cat

A more efficient way to read a file line by line in a shell script is to use the cat command in combination with a while loop. The cat command reads a file and outputs its contents to stdout, which can then be processed by the while loop. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(cat file.txt)

This method is more efficient than the read command because it reads the entire file into memory at once, rather than reading one line at a time. This can be faster for large files with many lines. In addition, the cat command can read from any file, not just stdin, so you can use it to read from multiple files or files that are not in the current directory.

Using while loop with sed

Another efficient way to read a file line by line in a shell script is to use the sed command in combination with a while loop. The sed command is a powerful text processing tool that can read a file and output its contents to stdout, one line at a time. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(sed -n -e 1p file.txt)

This method is similar to the cat command, but it is more efficient because it only outputs one line at a time. This can be faster for large files with many lines. In addition, the sed command has many options and features that can be used to manipulate the output, so it is a very flexible tool for text processing.

In summary, there are several ways to read a file line by line in a Linux shell script.

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/feed/ 0
How to list all collections in MongoDB database https://tecadmin.net/how-to-list-all-collections-in-mongodb-database/ https://tecadmin.net/how-to-list-all-collections-in-mongodb-database/#respond Sat, 30 Jul 2022 06:17:58 +0000 https://tecadmin.net/?p=30791 Question – How do I list all the collections available in the MongoDB database? MongoDB is a NoSQL database, that stores documents in JSON format. A collection is an entity in MongoDB (ie similar to a table in RDBMS databases) that stores JSON documents. You can use one of the below options to list collections [...]

The post How to list all collections in MongoDB database appeared first on TecAdmin.

]]>
Question – How do I list all the collections available in the MongoDB database?

MongoDB is a NoSQL database, that stores documents in JSON format. A collection is an entity in MongoDB (ie similar to a table in RDBMS databases) that stores JSON documents.

You can use one of the below options to list collections in a MongoDB database.

  • Mongo Shell: You can use one of the following commands from Mongo Shell to list all available collections in the MongoDB database. Before running the below commands you must be connected with the target database using use database_name.
    show collections 
    
    show tables 
    
    db.getCollectionNames() 
    
  • Node.js: Use listCollections() method to list all collections in database with Node.js application. The application must have created a connection to the MongoDB database before.
    db.listCollections()
    
  • JavaScript Shell: The JavaScript shell users can use the following method to list collections in the MongoDB database.
    db.getCollectionNames()
    

Thanks, hope this quick how-to guide helps you to find all collections in a MongoDB database.

The post How to list all collections in MongoDB database appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-list-all-collections-in-mongodb-database/feed/ 0
(Resolved) -bash: /bin/mv: Argument list too long https://tecadmin.net/mv-argument-list-too-long/ https://tecadmin.net/mv-argument-list-too-long/#comments Tue, 23 Nov 2021 02:42:20 +0000 https://tecadmin.net/?p=28334 One of my development servers contains millions of files under a single directory. To free the disk space, we decided to move to them a new folder created on another disk attached to the same system. When tried to move file with mv command, received the following error. -bash: /bin/mv: Argument list too long An [...]

The post (Resolved) -bash: /bin/mv: Argument list too long appeared first on TecAdmin.

]]>
One of my development servers contains millions of files under a single directory. To free the disk space, we decided to move to them a new folder created on another disk attached to the same system. When tried to move file with mv command, received the following error.

-bash: /bin/mv: Argument list too long

An argument list too long is a common problem with a bash that can happen when you have long command line parameters or arguments. You start running a script and it throws errors like “invalid command” or “too long”. The reason for this is that the shell is trying to read past the end of your argument list and there is no end of the input pipe to wait for. A system variable ARG_MAX defines the Maximum Character Length of Arguments In a shell command.

The Solution’s

The quick solution is to use xargs command line utility or find command with -exec … {}. Both commands break a large command into more minor and complete the job without errors.

  • find with xargs

    The following command will move all files with the “.txt” extension to the target directory. Here find will search all files with the “.txt” extension in the current directory as subdirectories. PIPE (|) will take the standard output of the find command and send it to the mv command as standard input. then mv will move files to the target directory one by one.

    find . -name '*.txt' | xargs mv --target-directory=/path/to/dest_dir/ 
    
  • find with exec

    Instead of using xargs, we can also use -the exec command. Here find will search files and exec will execute the mv command for each file one by one and move the file to the destination directory.

    find . -name '*.txt' -exec mv {} /path/to/dest_dir/ \;
    

    The default above commands will navigate recursively to the sub-directories. To limit the find to the current directory only use -maxdepth followed by a limit number to sub-directories.

    find . -name '*.txt' -maxdepth 1 -exec mv {} /path/to/dest_dir/ \;
    

The “Argument list too long” is a common error while handling a large number of files in bash scripts. You can find the max limit with the command getconf ARG_MAX on the shell.

The post (Resolved) -bash: /bin/mv: Argument list too long appeared first on TecAdmin.

]]>
https://tecadmin.net/mv-argument-list-too-long/feed/ 1
Bash Concatenate Strings https://tecadmin.net/bash-concatenate-strings/ https://tecadmin.net/bash-concatenate-strings/#respond Mon, 01 Nov 2021 11:10:22 +0000 https://tecadmin.net/?p=28295 Concatenating strings in Bash is as simple as combining them with the double-quote (“ ”) character. However, if your strings consist of more than a couple of words or include special characters, you may need to use a different method. Fortunately, the Bash programming language provides several methods for concatenating strings. This article explores five [...]

The post Bash Concatenate Strings appeared first on TecAdmin.

]]>
Concatenating strings in Bash is as simple as combining them with the double-quote (“ ”) character. However, if your strings consist of more than a couple of words or include special characters, you may need to use a different method. Fortunately, the Bash programming language provides several methods for concatenating strings.

This article explores five common ways to combine strings in your Bash scripts and programs. Keep reading to learn more about concatenating strings in Bash and which method is best for your specific situation.

Concatenate Strings

The simplest way to combine strings in Bash is to use the double-quote (“ ”) character. You can enclose your strings within double quotes and combine them to form a single string. This is useful for combining short strings that don’t require any special formatting. The example below demonstrates how to combine two short strings to form a single, long string using double quotes.

#/usr/bin/env bash
# A Sample shell script to concatenate strings 

# Declare variables
STR1="Welcome"
STR2="Tecadmin"

# Concatenate both strings 
STR3="$STR1$STR2"
echo "$STR3"

# You can even add a space between strings
STR3="$STR1 $STR2"  
echo "$STR3"

The echo command will print the result string.

Output
WelcomeTecadmin Welcome Tecadmin

Concatenate String Variable with Literal

A literal represents a fixed value. Instead of joining two string variables, we can also join a literal string with a variable value. For example, take an input of a user’s first name and prefix it with a “Welcome” literal string.

#/usr/bin/env bash

# A shell script to concatenate variable 
# with a literal string

# Take a user input and store to variable
read -p "What is your first name: " STR1

# Concatenate the string
STR2="Welcome ${STR1}"
echo "$STR2"

Execute the above script, It will prompt you to enter your Name. Then concatenate “Welcome” as a prefix to the input string and print the results.

Output
Enter your first name: Rahul Welcome Rahul

Concatenate Strings with += Operator

In general programming language the += adds the RHS value to LHS. You can also use this method to Concatenate the RHS string variable to the LHS string.

#/usr/bin/env bash
# A Sample shell script to concatenate strings 

# Delcare variable
STR="Welcome to"

# Concatenate another string to this variable.
STR+=" TecAdmin"

# Display the result string
echo $STR

This will print: Welcome to TecAdmin

Using the Printf Command

In bash, print is a command that is used to format and print data to standard output. The -v option initialize a variable with the output rather than print on output.

#/usr/bin/env bash

# A Sample shell script to concatenate strings 
# with the print command.

# Delcare variable
PREFIX="Hello Mr. "

# Concatenate another string to this variable.
printf -v STR "$PREFIX Rahul"

# Display the result string
echo $STR

This will print: Hello Mr. Rahul

Using loop

When there is an undefined number of the input strings, you need to concatenate them into a single string. The while loop will help you with the join (+=) operator.

For example, you need to read all lines of a file and concatenate them in a single string. To do this, we will read the file content line by line and concatenate them.

#/usr/bin/env bash

# A Sample shell script to concatenate strings 
# with a while loop

# Delcare variable
while read LINE; do
  STR+="$LINE "
done < data.txt

# Display the result string
echo $STR

Conclusion

This article explores five common ways to combine strings in your Bash scripts and programs. The simplest way to combine strings is to use the double-quote character. You can also use the for loop command to iterate through a series of words and combine them into a single string. The join (+) command is a Bash built-in that can be used to combine a series of items into a single string. The BASH scripting language allows you to perform more complex string operations including combining variables, calculations, and more.

The post Bash Concatenate Strings appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-concatenate-strings/feed/ 0
tee Command in Linux with Examples https://tecadmin.net/tee-command-in-linux-with-examples/ https://tecadmin.net/tee-command-in-linux-with-examples/#comments Tue, 26 Oct 2021 06:00:42 +0000 https://tecadmin.net/?p=28206 tee is a command in Linux that reads from standard input and writes the output to both standard output and one or more files, effectively duplicating the input. It is typically used in shell scripts to tee command output to both a file and the console. The Tee command in Linux is mostly used in [...]

The post tee Command in Linux with Examples appeared first on TecAdmin.

]]>
tee is a command in Linux that reads from standard input and writes the output to both standard output and one or more files, effectively duplicating the input. It is typically used in shell scripts to tee command output to both a file and the console.

The Tee command in Linux is mostly used in combination with other commands, it reads the input and in response to that writes the output to one or more files. It does this so that the output can be displayed as well as saved to a file at the same time. In this article, we will learn more about the tee command, from its syntax to its use along with examples to help you understand it better.

Linux tee command with examples

Syntax

The syntax of the tee command is provided below.

tee [OPTIONS]... [FILE]...

Here in this OPTIONS could be the following:

  • -a (–append): used to append to add to file and not overwrite it.
  • -i : in order to ignore the interrupt signals.

For [FILE] include the filename which can be one or more than one file.

Tee Command in Linux

The basic way in which the tee command is commonly used is to write to a file and display the output i.e stdout (standard output).

Users can write to a single as well as multiple files, hide output, they can append to a file without overwriting it, and also useful to ignore any interrupts while executing the file. Let’s understand these ones by one with examples.

  1. Write to a File
  2. We can use the tee command to write to a file and to demonstrate this we will use the command “df” to check the file system’s disk space and write all the information that we get as output in a file named “exFile.txt”.

    df -h | tee exFile.txt 
    

    Now go and check the file “exFile.txt” using the cat command.

    cat exFile.txt  
    

  3. Write To Multiple Files
  4. In order to write to multiple files, we’ll use the same above example but save the content into two different files. All you’ve to do is separate the file names by space.

    df -h | tee firstFile.out secondFile.out
    

    Now again if you check both the files using the cat command the content will be displayed.

    cat firstFile.out  
    
    cat secondFile.out  
    

    In this way, we can write to one or multiple files and save our output for later use.

  5. Append to a File
  6. This option “-a” is extremely useful as it helps in appending to a file without overwriting it. In this way, we can save the previous information and later add new information to the file. For this purpose first, we will create a file “helloFile.txt” and inside write “Hello”.

    echo "Hello"  | tee -a helloFile.txt  
    

    Now we’ll spend the word “World” in it.

    echo "World"  | tee -a helloFile.txt  
    

    Now, if we view the file using the cat command we will see that it appended the last word instead of overwriting it over the previous.

    cat helloFile.txt  
    

    In this way, we can append it into a file without overwriting it.

  7. Hide the Output
  8. In case you don’t want the output to be displayed on the terminal and simply save it in the file using the command “>/dev/null” along with the tee command.

    sudo echo "There?" | tee -a helloFile.txt >/dev/null  
    

    Later we checked the output using the cat command.

  9. Ignore any Interrupts
  10. Sometimes we want to execute a text file or any other format of the file but some interrupts occur and the process stops. To ignore these interrupts and want the tee to exit smoothly we use “-i” along with the tee command.

    In the example, we will ping google and use the interrupt command and while it’s executing we will interrupt it with CTRL+C.

    ping google.com | tee -i newFile.txt  
    

    Here you can see that while the command was running it was interrupted but still it executed smoothly. We can verify the content was added to the file by viewing the file using the cat command:

    cat newFile.txt  
    

  11. Using tee with Sudo
  12. In case you want to write to a file that belongs to root or a sudo user you have to use sudo along with the command.

    sudo echo "Please?" | sudo tee -a helloFile.txt  
    

    This way you can have access to the file easily.

Conclusion

Sometimes the user wants to write the output they get in the terminal to a file and for this purpose, the tee command is used. In this article we told you various ways how the tee command is used in Linux, we can write to multiple files as well as hide output or append to a file without overwriting it. Examples are provided in the case to help you understand the usage better of each command.

The post tee Command in Linux with Examples appeared first on TecAdmin.

]]>
https://tecadmin.net/tee-command-in-linux-with-examples/feed/ 1
How To Set/Create Environment and Shell variables in Linux https://tecadmin.net/how-to-set-create-environment-and-shell-variables-in-linux/ https://tecadmin.net/how-to-set-create-environment-and-shell-variables-in-linux/#respond Sat, 10 Jul 2021 07:00:18 +0000 https://tecadmin.net/?p=26586 Shell, the command interpreter of an OS, processes the commands entered into the command line and widely used in Linux. A variable is like a pointer to a particular data and holds a particular value that could be anything. A user can create, delete or assign variables with the help of Shell. When a Shell [...]

The post How To Set/Create Environment and Shell variables in Linux appeared first on TecAdmin.

]]>
Shell, the command interpreter of an OS, processes the commands entered into the command line and widely used in Linux. A variable is like a pointer to a particular data and holds a particular value that could be anything. A user can create, delete or assign variables with the help of Shell.

When a Shell is running there are three types of variables present:

  1. Local Variables
  2. Shell variables
  3. Environment variables

In this tutorial, we will see how you can set Environment and Shell variables in Linux.

What are Shell Variables?

The Shell variables are specific to the current shell and used by the Shell to function correctly. These variables are temporary, and to make them permanent you can export them as environment variables.

Some of the common shell variables are:

  • UID: Current logged in user’s ID
  • HOSTNAME: The hostname of the computer at a particular time
  • BASH_VERSINFO: Machine-readable form of bash version
  • BASH_VERSION: Human-readable output of bash version
  • DIRSTACK: Stack of directories available with ‘popd’ and ‘pushd’ command
  • SHELLOPTS: Shell options can be set

What are Environment Variables?

Environment Variables are system-wide available variables that are available to any program or child process of the shell. Also, the Shell Script defines the environment variables that are needed to run the program.

Some of the common Environment variables are:

  • MAIL: Mail directory of the user or the path to user’s mailbox
  • TEMP: Temporary files’ director location
  • PWD: Current working directory
  • OLDPWD: The previous working directory
  • USER: The current user logged in
  • LANG: The current language
  • LOGNAME: User Name
  • HOME: The home directory of the current user
  • _: Recent previous command executed
  • SHELL: The current shell
  • EDITOR: The default text editor of Linux
  • HOSTNAME: The hostname of the device on the network

Here are some of the commands that will help you in setting Shell and Environment variables:

  • env: You can use a custom environment to run another program without modifying the existing environment.
  • printenv: This will print all the environment variables of your system.
  • set: Used to set the environment and shell variables.
  • unset: Used to delete the environment and shell variables.
  • exports: Let’s you export shell variables into environment variables.

How to print Shell and Environment variables?

Shell keeps a track of all Environment and Shell variables. And to access that we can use these two commands:

  • printenv: to print all the Environment variables.
  • set: to print Shell variables.

How to set Environment and Shell variables in Linux?

So now we know that what Environment and Shell variables are. So let’s learn how to create and set these variables in Linux. To clearly understand the difference between Environment and Shell variables practically. We will first set a Shell variable and then the Environment variable.

Creating the Shell variable

  • To set a Shell variable run this command in your Shell. This will create a Shell variable that will be available in your current session.
    TESTVAR='Hello!' 
    
  • We can also check our variable with the grep command.
    set | grep TESTVAR
    

    You will see an output like this.

    TESTVAR='Hello!'
    
  • You can also see the value of a shell variable with the following command.
    echo $TESTVAR
    
  • As it is a Shell variable, so it will not be available for other applications or child processes. You can even verify that it is not an Environment variable.
    printenv | grep TESTVAR
    

    There will be no output. It means it is not an Environment variable.

Creating the Environment Variables

  • Now, let’s export the Shell variable into an Environment variable. Use the following command to do that.
    export TESTVAR 
    
  • This will turn our Shell variable into an Environment variable and to verify that run the following command.
    printenv | grep TESTVAR 
    

    This time you will see an output like this.

    TESTVAR='Hello!'
    
  • Now we know that how we can convert a Shell variable into an Environment variable but how to create an Environment variable directly. You can set an Environment variable in a single step with this command.
    export NEWVAR="Hello Env" 
    
  • It will be directly exported as an Environment variable and you can verify that.
    printenv | grep NEWVAR 
    

    You will see an output like this.

    NEWWAR=Hello Env 
    

This way you can set Shell and Environment in Linux.

Unsetting variables

Now you know that how to set variables. Let’s learn about unsetting them.

  • You can change an Environment variable into a Shell variable again with this command.
    export -n TESTVAR 
    
  • It will remain a Shell variable but not an Environment variable. Let’s verify that.
    printenv | grep TESTVAR 
    
  • There will be no output but if we check it for the Shell variable,
    set | grep TESTVAR 
    

    you will see the output.

    TESTVAR='Hello!'
    
  • And if you want to completely unset that then use this command.
    unset TESTVAR 
    

Conclusion

Environment and Shell variables can be very useful for you if you often work with Shell and learning how to set and unset these variables will be good from a long-term perspective.

The post How To Set/Create Environment and Shell variables in Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-set-create-environment-and-shell-variables-in-linux/feed/ 0
How to Install ZSH (Z Shell) on Ubuntu 20.04 https://tecadmin.net/how-to-install-zsh-on-ubuntu-20-04/ https://tecadmin.net/how-to-install-zsh-on-ubuntu-20-04/#respond Sun, 23 Aug 2020 09:23:40 +0000 https://tecadmin.net/?p=22453 The Zsh (Z shell) is a interactive login shell for the Unix/Linux systems. It has multiple improvement over the Bash shell and includes the best features of the Bash, ksh and tcsh shells. This tutorial will help you to install ZSH on Ubuntu 20.04 LTS Linux system. Installing ZSH on Ubuntu Zsh packages are available [...]

The post How to Install ZSH (Z Shell) on Ubuntu 20.04 appeared first on TecAdmin.

]]>
The Zsh (Z shell) is a interactive login shell for the Unix/Linux systems. It has multiple improvement over the Bash shell and includes the best features of the Bash, ksh and tcsh shells. This tutorial will help you to install ZSH on Ubuntu 20.04 LTS Linux system.

A Running Zsh Shell on Ubuntu
A Running Zsh Shell on Ubuntu

Installing ZSH on Ubuntu

Zsh packages are available under the default apt repositories. So first, update the Apt cache on your system with latest available packages.

sudo apt update 

Then type below command to install zsh shell packages with required dependencies.

sudo apt install zsh

Installing ZSH on Ubuntu 20.04

Once the installation completed, let’s check the installed Zsh shell version by running command:

zsh --version

Check ZSH Shell Version on Ubuntu 20.04

Installing Oh-My-Zsh Plugin

On-My-Zsh plugin provides a large number of customization for the Z shell. So without this plugion Zsh plugin is incomplete. So we also recommend to install this plugin on with Zsh shell.

sudo apt install git-core curl fonts-powerline 

Oh-My-Zsh provides a shell script for the installation on Linux systems. Execute the following command to install this plugion on your system.

sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" 

This will ask you to setup Zsh as default set. You can access or reject this as your choice. After that installation will complete within few seconds.

You may like to change Zsh theme by editiog ~/.zshrc file on your system. You can select a theme from here.

sudo vi ~/.zshrc 

Set theme name to ZSH_THEME environment variable.

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes

ZSH_THEME="agnoster"

Save file and close it. Then launch a new shell to apply changes.

Launch Zsh Shell Terminal

To launch a Zsh shell terminal just type “zsh” from your current shell.

zsh 

Start a new Z shell terminal

Conclusion

In this tutorial, you have learned about installation off Zsh shell on Ubuntu system. Also installed Oh-My-Zsh plugin on your system.

The post How to Install ZSH (Z Shell) on Ubuntu 20.04 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-zsh-on-ubuntu-20-04/feed/ 0