help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Putting escaped elements in an array


From: Eduardo A . Bustamante López
Subject: Re: [Help-bash] Putting escaped elements in an array
Date: Sun, 27 Apr 2014 10:35:35 -0700
User-agent: Mutt/1.5.21 (2010-09-15)

On Sun, Apr 27, 2014 at 03:35:38PM +0200, Jesper Nygårds wrote:
> I wanted to keep an array of directories that I have visited, and for this
> array to be automatically updated. I therefore wrote the following:
> 
> PROMPT_COMMAND=_push-dir
> 
> declare lastdir
> declare -a dirstack
> 
> _push-dir () {
>     local currentdir=$(ls -d --quoting-style=escape "$(readlink -e .)")
>     if [[ -n $lastdir && "$lastdir" != "$currentdir" ]]; then
>         eval dirstack=( $(printf "%q" "$lastdir") $(printf "%q "
> "address@hidden") )
>     fi
>     lastdir="${currentdir}"
> }

PROMPT_COMMAND=_push_dir
lastdir=
dirstack=()

_push_dir() {
  local currentdir
  currentdir=$(readlink -e .; printf x) currentdir=${currentdir%?}
  if [[ -d $lastdir && $lastdir != "$currentdir" ]]; then
    dirstack=("$lastdir" "address@hidden")
  fi
  lastdir=$currentdir
}



1) the key to getting weird filenames to work is learn how to quote
properly.
2) don't use that ls stuff + eval stuff, you're just complicating
yourself. The shell is perfectly capable of dealing with any possible
character in a filename.
3) read: <http://mywiki.wooledge.org/Quotes>
4) there are some exceptions to quoting (i.e. where quoting is not
really needed):
- in [[ FOO = BAR ]], you only have to quote BAR, not FOO (doesn't
  hurt to do it though)
- in FOO=BAR, BAR doesn't need quoting. No word splitting ocurrs in
  scalar assignment (not the same case for arrays)
- in 'case VAR in ...'
- and other exceptions I can't remember. Everywhere else make sure
  you always quote correctly your expansions, or the shell is going
  to mess with your whitespace.
5) Avoid using - and other special characters in bash function names,
it's just supported for backwards compatibility, but it shouldn't
really be allowed. And it's not documented.
6) the foo=$(cmd; printf x) foo=${foo%?} trick is used to avoid the
$(...) to remove trailing newlines. Just in case you have filenames
that weird.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]