r/commandline • • Aug 17 '15

Bash Pitfalls - This page shows common errors that Bash programmers make.

http://mywiki.wooledge.org/BashPitfalls
64 Upvotes

8 comments sorted by

6

u/criswell Aug 17 '15

2

u/ray_gun Aug 17 '15

Generally, the for file in * is easier to write as well, but when you want specific sorted data, ls is very useful and I don't think parsing ls deserves such hate, when you can do things like: IFS=$'\n'; mplayer $(ls -t) (to play recent movies e.g.), even in a public script.

1

u/UnchainedMundane Aug 20 '15

You can do that, but it won't play nice with special characters.

Try this:

touch '*' '**' '***' 'x
y' 'x?y'

and then check the result of:

IFS=$'\n'; printf '<%s> ' $(ls -t); printf \\n

3

u/Araneidae Aug 17 '15

I so wish we could forbid '\n' from file names. It's the only really troublesome one (though forbidding all characters in the range 0x01 to 0x1F would make so much sense).

5

u/galaktos Aug 17 '15 edited Aug 17 '15

I kinda want to use debugfs or a similar tool to create a file with \0 in the name (a null byte). Directory entries include the name length (at least in Ext4, see ext4_dir_entry in fs/ext4/ext4.h), so it’s not impossible… but I suspect that a huge amount of stuff written in C and using null-terminated strings will break. Should be a lot of fun :)

2

u/zebediah49 Aug 18 '15

That distinctly has the potential to destroy so many things -- it wouldn't surprise me if you ended up with an un-deletable file.

Alternatively if it was sufficiently broken the filename->inode calculation might also not fully handle it, and so you might end up with it still working fine under a shorter name.

.... which, if true, would mean that you could conceal data inside a filename by placing it after than \0

1

u/lolmeansilaughed Aug 18 '15

Regarding #29 - sed commands can get so complicated, I think it's worth mentioning that, rather than something like this:

sed "s/home\/$user\/code\/$somedir//g" 

You could more simply do something like this:

sed 's!home/'"$user"'/code/'"$somedir"'!!g' 

Although maybe beauty is in the eye of the beholder ;)

Also side note the author must not spend much time in the shell itself if he doesn't use history expansion.