Details would be appreciated!

I know that it supposed to be a shell script or something like that, but it would be greateful if someone more experienced in this field can tell me more about it.

echo "" >> $HOME/.bashrc && echo "function cdls { cd "$1"; ls --color;}" >> $HOME/.bashrc

"echo" will (as the name states) echo a string of text to std out (usually the screen).

">>" will append the output of the preceding command to a file path.

"&&" will run (based on the successful exit of the previous command) the successive command.

";" will run (regardless of the successful exit of the previous command) the successive command.

"function" will create a function that will run in the Bash Shell.

"$HOME" is a reference (Bash Variable) to the user's OS home directory automatically created by Bash.

".bashrc" is a hidden file (in the user's home directory) that is run when the user starts an interactive session. It is often used for customizing the bash shell at the user-level.

"cd" is a directory change, change working directory.

"ls" lists files in the directory. In this case "--color" is an argument that will emphasize certain directory elements with color, rather than using a single color.

"$1" is used to allow a user to pass an argument to this command as a variable.

So, in short, for...

echo "" >> $HOME/.bashrc &&
   echo "function cdls { cd "$1"; ls --color;}" >> $HOME/.bashrc

The first line appends an "empty" line to .bashrc - simply for clarity's sake when someone looks at the file in the future. The second line appends a new function called "cdls" which accepts an argument (a directory name), then changes the working directory to this location, and then immediately runs the "ls" command on this directory.

EDIT: Please see comments from Celada and derobert on steve's answer.


Test whether $HOME/.bashrc is writable, by trying to append nothing to it:

echo "" >> $HOME/.bashrc &&

If the test is successful, the file is writable, append a function to it. So that running cdls foo will display a coloured directory listing of directory "foo".

echo "function cdls { cd "$1"; ls --color;}" >> $HOME/.bashrc
  • Will it though? Won't it cd into whatever $1 was expanded to at the time the function was appended to .bashrc? – Celada Apr 10 '17 at 20:18
  • Indeed, the quoting is wrong too: should be cd \"$1\" — or better, the whole thing should be in single quotes, not double quotes, fixing both problems. – derobert Apr 10 '17 at 20:21
  • Also, rather than destructively adding newlines, [[ -w $HOME/.bashrc ]] would probably be a better test. – DopeGhoti Apr 10 '17 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.