Skip to content

Commit 72b3b2e

Browse files
committed
l: propagate exit status from ls
Previously the exit status from this script was that of the final sed(1), which is usually success, even if specified files can't be found etc. Instead use the exit code from the wrapped ls command. `set -o pipefail` would be an elegant way to achieve that, but that's bash/ksh/zsh specific, so we manually setup file descriptors so that the exit status from ls can be manually output and captured.
1 parent 2bff701 commit 72b3b2e

File tree

1 file changed

+20
-3
lines changed
  • scripts

1 file changed

+20
-3
lines changed

scripts/l

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# Don't error for ls without --group-dir or --no-group
1515
# V0.3, 21 Oct 2009, Handle older ls' which pepper output with reset codes
1616
#
17-
# V1.1, 05 Jun 2014
17+
# V1.2, 12 Oct 2016
1818
# http://github.com/pixelb/scripts/commits/master/scripts/l
1919

2020
# apply thousands separator to file sizes
@@ -138,9 +138,17 @@ $ls --no-group -d . >/dev/null 2>&1 && ng=--no-group
138138
lfmt=lfmt
139139
echo "$*" | grep -E -- "-(m|i|x|s|C|-version|-help)" >/dev/null && lfmt=""
140140

141+
# set -o pipefail is bash/ksh/zsh specific
142+
# So manually propagate the exit status from ls.
143+
# See http://stackoverflow.com/a/30658405/4421
144+
145+
exec 4>&1
146+
ls_status=`{ {
147+
141148
# Start with the standard long format listing
142149
# with colours, and latest files at bottom
143-
$ls -lrtq $color_opt$color_when $ng $gdf "$@" |
150+
$ls -lrtq $color_opt$color_when $ng $gdf "$@";
151+
printf $? 1>&3; } |
144152
145153
# process with sed to...
146154
sed "
@@ -181,4 +189,13 @@ sed "
181189
182190
# restore any reset codes replaced above
183191
s/^0/${ESC}[0m/
184-
"
192+
" 1>&4; } 3>&1`
193+
194+
sed_status=$?
195+
196+
# Note if sed fails, then if ls outputs it will usually get
197+
# a SIGPIPE and exit with status 141. Though that's dependent
198+
# on ls(1) propagating that "error", and also will not be the case
199+
# if ls does not output after sed terminates. So factor both
200+
# exit values into the final exit status.
201+
test $ls_status != 0 && exit $ls_status || exit $sed_status

0 commit comments

Comments
 (0)