cbutler
cbutler

Reputation: 25

How do I write a script that shows all aliases upon startup of terminal

I am a new user learning to use Linux. I am currently running Ubuntu 18.04 with several aliases created, and saved in the ~/.bashrc directory. I am trying to write a welcome script that also displays the current aliases upon start up. The current code I have is as follows:

    #! /bin/bash
    echo -e "\nWelcome $USER"
    echo -e "Today's date is: \c"
    date
    echo -e "\vHave \vA \VGreat \vDay! \c"
    echo -e "\nCurrent aliases for reference are:"
    alias

Upon startup, or running the script on it's own, the welcome message runs but the actual alias command does not?

Upvotes: 2

Views: 875

Answers (1)

mtnezm
mtnezm

Reputation: 1027

First things first:

(...) saved in the ~/.bashrc directory. (...)

Well, I must point that .bashrc is a file, not a directory, and is part of the Bash startup files.

That said, the reason why running the alias command inside a script does not work as expected is that it is a shell builtin, and when invoking it from a script will not behave as if running it from your shell.

Hence, the quickest thing you can do is store your aliases in a different file, like ~/.bash_aliases and ensure it will be loaded by adding this to your .bashrc file:

if [ -f ~/.bash_aliases ]; then
    source ~/.bash_aliases
fi

And then read that file directly from your script:

#! /bin/bash

echo -e "\nWelcome $USER"
echo -e "Today's date is: \c"
date
echo -e "\vHave \vA \VGreat \vDay! \c"
echo -e "\nCurrent aliases for reference are:"
cat ~/.bash_aliases

Upvotes: 1

Related Questions