Skip to content

Instantly share code, notes, and snippets.

@mika
Created July 31, 2014 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mika/9eb2325c4c8ab0127c29 to your computer and use it in GitHub Desktop.
Save mika/9eb2325c4c8ab0127c29 to your computer and use it in GitHub Desktop.
Fun with shell code
Code broken in all Zsh versions and Bash versions older than 4.3:
% cat ./foo.sh
DISK_LIST=$(for i in $AVAILABLE_DISKS ; do
for file in /dev/disk/by-id/* ; do
case "$(realpath $file)" in
/dev/"$i") disk_info="${file#/dev/disk/by-id/}" ; break ;;
*) disk_info="${file}" ;;
esac
done
echo "${i}" "${disk_info}"
done)
% bash -n ./foo.sh
./foo.sh: line 4: syntax error near unexpected token `;;'
./foo.sh: line 4: ` /dev/"$i") disk_info="${file#/dev/disk/by-id/}" ; break ;;'
% bash --version | head -1
GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)
% bash -n ./foo
./foo: line 4: syntax error near unexpected token `;;'
./foo: line 4: ` /dev/"$i") disk_info="${file#/dev/disk/by-id/}" ; break ;;
% bash --version | head -1
GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
% zsh -n ./foo.sh
./foo.sh:4: parse error near `;;'
% zsh --version
zsh 5.0.5 (x86_64-pc-linux-gnu)
Works fine in Bash >=4.3, ksh93, mksh + pdksh though:
% bash -n ./foo.sh
% bash --version | head -1
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Change that makes code parseable and executable in any Shell:
% git diff
diff --git a/foo.sh b/foo.sh
index ea3eb84..6491f54 100644
--- a/foo.sh
+++ b/foo.sh
@@ -1,8 +1,8 @@
DISK_LIST=$(for i in $AVAILABLE_DISKS ; do
for file in /dev/disk/by-id/* ; do
case "$(realpath $file)" in
- /dev/"$i") disk_info="${file#/dev/disk/by-id/}" ; break ;;
- *) disk_info="${file}" ;;
+ (/dev/"$i") disk_info="${file#/dev/disk/by-id/}" ; break ;;
+ (*) disk_info="${file}" ;;
esac
done
echo "${i}" "${disk_info}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment