Skip to content

Instantly share code, notes, and snippets.

@fourdollars
Last active November 2, 2015 07:31
Show Gist options
  • Save fourdollars/47424ed5ee05679f05c7 to your computer and use it in GitHub Desktop.
Save fourdollars/47424ed5ee05679f05c7 to your computer and use it in GitHub Desktop.
Please replace [...] with your code snippets. This script will be used in busybox to find out the partitions by following the specific order.
#!/bin/sh
PARTITIONS="/dev/mmcblk0p1 /dev/mmcblk1p1 /dev/nvm0n1p1 /dev/nvm0n2p1 /dev/sda1 /dev/sdb1"
DEVICES="/dev/sdb /dev/nvm0n2 /dev/nvm0n1 /dev/mmcblk0"
result=""
[...] # can not use PARTITIONS here
for partition in $PARTITIONS; do
[...]
done
[...] # can not use PARTITIONS here
# Expected result: /dev/sdb1 /dev/nvm0n2p1 /dev/nvm0n1p1 /dev/mmcblk0p1
echo $result
@fourdollars
Copy link
Author

我想到的是這樣

candidates=""

for partition in $PARTITIONS; do
  for device in $DEVICES; do
    case "$partition" in
      $device*)
        candidates="$candidates $partition"
        ;;
    esac
  done
done

for device in $DEVICES; do
  for candidate in $candidates; do
    case "$candidate" in
      $device*)
        if [ -z "$result" ]; then
          result="$candidate"
        else
          result="$result $candidate"
        fi
        ;;
    esac
  done
done

@fourdollars
Copy link
Author

另一個更簡單的版本,雖然無法直接存取 PARTITIONS 的值,但是可以先用另一個變數存起來之後再使用。 XD

candidates=""

for partition in $PARTITIONS; do
  if [ -z "$candidates" ]; then
    candidates="$partition"                
  else
    candidates="$candidates $partition"
  fi
done

for device in $DEVICES; do
  for candidate in $candidates; do
    case "$candidate" in
      $device*)
        if [ -z "$result" ]; then
                result="$candidate"
        else
                result="$result $candidate"
        fi
        ;;
    esac
  done
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment