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
@likueimo
Copy link

如果有人可以幫我想不用產出res.tmp方法
希望可以告知謝謝!

for partition in $PARTITIONS
  do
        for d in $DEVICES
                do
                ppl=`echo $partition | grep $d | grep -v p2`   
                #use grep to search DEVICES and -v to inverse-match p2
                if [ ! -z "$ppl" ];then echo  $ppl" "; fi >> res.tmp # not null to output res.tmp
                done
  done

result=`tac res.tmp | tr -d '\n' ` #reverse res.tmp
echo "result:" $result
rm res.tmp 

output print:

result: /dev/sdb1 /dev/nvm0n2p1 /dev/nvm0n1p1 /dev/mmcblk0p1

@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