user42826
user42826

Reputation: 101

works on commandline directly, but complaints syntax error when aliased in bash

Here's the command, I am trying to run on bash, it works great. But when I aliased and put in the bashrc, it complaints of a syntax error.

  alias dsh="for i in `ls -d */`;do echo $i; du -sh $i;done"

Upvotes: 1

Views: 49

Answers (3)

hek2mgl
hek2mgl

Reputation: 158020

Basically you need to use single quotes. Otherwise ls -d */ and $i get's expanded in the shell where you define the alias, not in the shell where you execute that alias.

alias dsh='for i in `ls -d */`;do echo "$i"; du -sh "$i";done'

However, iterating over the results of ls is not recommended. If a folder name returned by ls contains spaces, the for i in loop wouldn't handle it properly. That's why I suggest to use find

alias dsh='find -maxdepth 1 -type d -exec du -sh {} \;'

Note that du -sh will print the folder name. No further echo is required.


tripleee posted an answer here showing that using find is a bit too complicated. He suggests to use du -sh */. This looks like the best approach for me. I would go with it.

Upvotes: 2

tripleee
tripleee

Reputation: 189427

Inside double quotes, the command substitution in backticks will get evaluated by the shell immediately. The obvious workaround is to switch to single quotes, which inhibit this. But you can avoid the backticks and the useless ls with the simpler and more elegant for i in */.

However, you don't need a loop here at all; like most Unix utilities which take file name arguments, du accepts an arbitrary number of them: du -sh */

Upvotes: 4

heemayl
heemayl

Reputation: 42017

Use single quotes instead of double quotes and also instead of ls -d */ use just */:

alias dsh='for i in */;do echo "$i"; du -sh "$i"; done'

Upvotes: 2

Related Questions