customisation

All posts tagged customisation by Linux Bash
  • Posted on

    Working with Environment Variables in Bash

    Environment variables in Bash are variables that define the environment in which processes run. They store system-wide values like system paths, configuration settings, and user-specific data, and can be accessed or modified within a Bash session.

    Environment variables are essential for: - Configuring system settings. - Customizing the behavior of scripts and programs. - Storing configuration values for users and applications.

    Here’s an overview of how to work with environment variables in Bash.


    1. Viewing Environment Variables

    To see all the current environment variables, use the env or printenv command:

    env
    

    or

    printenv
    

    This will print a list of all environment variables and their values.

    To view a specific variable:

    echo $VARIABLE_NAME
    

    Example:

    echo $HOME
    

    This will display the path to the home directory of the current user.


    2. Setting Environment Variables

    To set an environment variable, you can use the export command. This makes the variable available to any child processes or scripts launched from the current session.

    Syntax:

    export VARIABLE_NAME="value"
    

    Example:

    export MY_VAR="Hello, World!"
    

    Now, the MY_VAR variable is available to the current session and any child processes.

    To check its value:

    echo $MY_VAR
    

    3. Unsetting Environment Variables

    If you no longer need an environment variable, you can remove it with the unset command.

    Syntax:

    unset VARIABLE_NAME
    

    Example:

    unset MY_VAR
    

    After running this command, MY_VAR will no longer be available in the session.


    4. Temporary vs. Permanent Environment Variables

    Temporary Environment Variables:

    Environment variables set using export are only valid for the duration of the current shell session. Once the session ends, the variable will be lost.

    Permanent Environment Variables:

    To set an environment variable permanently (so that it persists across sessions), you need to add it to one of the shell initialization files, such as: - ~/.bashrc for user-specific variables in interactive non-login shells. - ~/.bash_profile or ~/.profile for login shells.

    Example: Setting a permanent variable

    1. Open the file for editing (e.g., ~/.bashrc):

      nano ~/.bashrc
      
    2. Add the export command at the end of the file:

      export MY_VAR="Permanent Value"
      
    3. Save the file and reload it:

      source ~/.bashrc
      

    Now, MY_VAR will be available every time a new shell is started.


    5. Common Environment Variables

    Here are some common environment variables you’ll encounter:

    • $HOME: The home directory of the current user.
    • $USER: The username of the current user.
    • $PATH: A colon-separated list of directories where executable files are located.
    • $PWD: The current working directory.
    • $SHELL: The path to the current shell.
    • $EDITOR: The default text editor (e.g., nano, vim).

    Example:

    echo $PATH
    

    This will print the directories that are included in your executable search path.


    6. Using Environment Variables in Scripts

    Environment variables can be used within Bash scripts to customize behavior or store settings.

    Example Script:

    #!/bin/bash
    
    # Use an environment variable in the script
    echo "Hello, $USER! Your home directory is $HOME"
    

    You can also pass variables into scripts when you run them:

    MY_VAR="Some Value" ./myscript.sh
    

    Inside myscript.sh, you can access $MY_VAR as if it were set in the environment.


    7. Modifying $PATH

    The $PATH variable is a crucial environment variable that defines the directories the shell searches for executable files. If you install new software or custom scripts, you may want to add their location to $PATH.

    Example: Adding a directory to $PATH

    export PATH=$PATH:/path/to/my/custom/bin
    

    This command appends /path/to/my/custom/bin to the existing $PATH.

    To make this change permanent, add the export command to your ~/.bashrc or ~/.bash_profile.


    8. Environment Variables in Subshells

    When you open a new subshell (e.g., by running a script or launching another terminal), the environment variables are inherited from the parent shell. However, changes to environment variables in a subshell will not affect the parent shell.

    For example:

    export MY_VAR="New Value"
    bash  # Open a new subshell
    echo $MY_VAR  # This will show "New Value" in the subshell
    exit
    echo $MY_VAR  # The parent shell's $MY_VAR is unaffected
    

    9. Example of Using Multiple Environment Variables in a Script

    #!/bin/bash
    
    # Setting multiple environment variables
    export DB_USER="admin"
    export DB_PASSWORD="secret"
    
    # Using the variables
    echo "Connecting to the database with user $DB_USER..."
    # Here, you would use these variables in a real script to connect to a database, for example.
    

    Conclusion

    Working with environment variables in Bash is a key part of managing system configuration and making your scripts flexible and portable. By using commands like export, echo, and unset, you can configure, view, and manage variables both temporarily and permanently. Mastering environment variables will help you manage your Linux environment more effectively, automate tasks, and write more dynamic Bash scripts.

  • Posted on

    Creating and Using Bash Aliases for Faster Commands

    A Bash alias is a shortcut for a longer command or a sequence of commands. Aliases help improve productivity by saving time and effort. Here's a guide to creating and using Bash aliases:


    1. Temporary Aliases

    Temporary aliases are created in the current shell session and last until the terminal is closed.

    Syntax:

    alias alias_name='command'
    

    Examples:

    • Create a short alias for listing files: bash alias ll='ls -al'
    • Create an alias to navigate to a frequently used directory: bash alias docs='cd ~/Documents'
    • Create an alias to remove files without confirmation: bash alias rmf='rm -rf'

    Using Temporary Aliases:

    Once created, type the alias name to execute the command:

    ll    # Equivalent to 'ls -al'
    docs  # Changes directory to ~/Documents
    

    2. Permanent Aliases

    To make aliases persist across sessions, add them to your shell's configuration file. The most common file is ~/.bashrc, but it could also be ~/.bash_profile or another file depending on your system setup.

    Steps to Create Permanent Aliases:

    1. Open your shell configuration file: bash vi ~/.bashrc
    2. Add the alias definition at the end of the file: bash alias ll='ls -al' alias docs='cd ~/Documents' alias gs='git status'
    3. Save and exit the file.
    4. Reload the configuration file to apply changes: bash source ~/.bashrc

    3. Viewing Existing Aliases

    To see all active aliases in the current shell session, use:

    alias
    

    If you want to check the definition of a specific alias:

    alias alias_name
    

    Example:

    alias ll
    # Output: alias ll='ls -al'
    

    4. Removing an Alias

    To remove a temporary alias in the current session, use:

    unalias alias_name
    

    Example:

    unalias ll
    

    To remove a permanent alias, delete its definition from ~/.bashrc and reload the configuration:

    vi ~/.bashrc
    # Delete the alias definition, then:
    source ~/.bashrc
    

    5. Advanced Alias Tips

    • Use Parameters with Functions:
      If you need an alias that accepts arguments, use a shell function instead:

      myfunction() {
      ls -l "$1"
      }
      alias ll='myfunction'
      
    • Chaining Commands in Aliases:
      Combine multiple commands using && or ;:

      alias update='sudo apt update && sudo apt upgrade -y'
      
    • Conditional Aliases:
      Add logic to aliases by wrapping them in functions:

      alias checkdisk='df -h && du -sh *'
      

    6. Examples of Useful Aliases

    • Simplify ls commands: bash alias l='ls -CF' alias la='ls -A' alias ll='ls -alF'
    • Git shortcuts: bash alias gs='git status' alias ga='git add .' alias gc='git commit -m' alias gp='git push'
    • Networking: bash alias myip='curl ifconfig.me' alias pingg='ping google.com'
    • Custom cleanup command: bash alias clean='rm -rf ~/.cache/* && sudo apt autoremove -y'

    Conclusion

    Using aliases can greatly speed up your workflow by reducing repetitive typing. Start with simple aliases for your most-used commands and progressively add more as you identify opportunities to save time. With permanent aliases, you’ll have a customized environment that boosts efficiency every time you open the terminal.

  • Posted on

    How to Customise Your Bash Prompt for Better Productivity

    The Bash prompt is the text that appears in your terminal before you type a command. By default, it displays minimal information, such as your username and current directory. Customizing your Bash prompt can enhance productivity by providing quick access to important information and making your terminal visually appealing.


    What is the Bash Prompt?

    The Bash prompt is controlled by the PS1 variable, which defines its appearance. For example:

    PS1="\u@\h:\w\$ "
    
    • \u: Username.
    • \h: Hostname.
    • \w: Current working directory.
    • \$: Displays $ for normal users and # for the root user.

    Why Customise Your Bash Prompt?

    1. Enhanced Information: Display details like the current Git branch, exit status of the last command, or time.
    2. Improved Visuals: Use colors and formatting to make the prompt easier to read.
    3. Increased Productivity: Quickly identify useful information without typing additional commands.

    Steps to Customise Your Bash Prompt

    1. Temporary Customization

    You can modify your prompt temporarily by setting the PS1 variable:

    PS1="\[\e[32m\]\u@\h:\w\$\[\e[0m\] "
    

    This changes the prompt to green text with the username, hostname, and working directory.

    2. Permanent Customisation

    To make changes permanent:

    1. Edit the .bashrc file in your home directory: bash vi ~/.bashrc
    2. Add your custom PS1 line at the end of the file.
    3. Save and reload the file: bash source ~/.bashrc

    Common Customizations

    Add Colors

    Use ANSI escape codes for colors:

    • \[\e[31m\]: Red

    • \[\e[32m\]: Green

    • \[\e[34m\]: Blue

    • \[\e[0m\]: Reset to default color.

    Example:

    PS1="\[\e[34m\]\u@\h:\[\e[32m\]\w\$\[\e[0m\] "
    

    This makes the username and hostname blue and the working directory green.

    Include Time

    Display the current time:

    PS1="\[\e[33m\]\t \[\e[34m\]\u@\h:\w\$ \[\e[0m\]"
    
    • \t: Time in HH:MM:SS format.

    • \@: Time in 12-hour AM/PM format.

    Show Git Branch

    Display the current Git branch when inside a repository:

    PS1="\[\e[32m\]\u@\h:\[\e[34m\]\w\[\e[31m\]\$(__git_ps1)\[\e[0m\] \$ "
    
    • Ensure you have Git installed and the git-prompt.sh script sourced in your .bashrc file.

    Add Command Exit Status

    Show the exit status of the last command:

    PS1="\[\e[31m\]\$? \[\e[34m\]\u@\h:\w\$ \[\e[0m\]"
    
    • \$?: Exit status of the last command.

    Advanced Customisations with Tools

    Starship

    Starship is a modern, highly customizable prompt written in Rust. Install it and add this line to your .bashrc:

    eval "$(starship init bash)"
    

    Best Practices for Customizing Your Prompt

    1. Keep it Simple: Avoid cluttering the prompt with too much information.
    2. Use Colors Sparingly: Highlight only the most critical details.
    3. Test Changes: Test new prompts before making them permanent.
    4. Backup Your .bashrc: Keep a backup before making extensive changes.

    Example Custom Prompt

    Here’s a full-featured example:

    PS1="\[\e[32m\]\u@\h \[\e[36m\]\w \[\e[33m\]\t \[\e[31m\]$(git_branch)\[\e[0m\]\$ "
    
    • Green username and hostname.
    • Cyan working directory.
    • Yellow current time.
    • Red Git branch (requires Git integration).

    Customizing your Bash prompt is a great way to make your terminal more functional and visually appealing. Experiment with different configurations and find the one that works best for you!