patternbashMinor
Mounting multiple partitions on a disk
Viewed 0 times
diskpartitionsmountingmultiple
Problem
Is it possible to improve the code of this bash script? ... or should I just use another language? (If so, which one would fit the best the situation, according to you?)
Here is the code (simplified, to emphasis the problem):
To me, this code is redundant. Is there any more efficient/better way to do it ?
Which language should I use for this task?
Here is the code (simplified, to emphasis the problem):
#!/bin/bash
# mountDDE mount the partitions of the disk b.
# If arguments are passed, it will mount the specific partitions, a, b or c.
if [ -v "$1" ] # If no argument is passed, act on all partitions.
then a=t
b=t
c=t
fi
while [ -n "$1" ] ; do
if [ $1="a" ] # We test the argument(s), to know which partition has to be mounted.
then a=t
elif [ $1="b"] # I hate redundunces
then b=t
elif [ $1="c"] # Again...
then c=t
fi
shift
done
[ $a="t" ] && sudo mount /dev/sba /media/ba # I'll actually use uuids.
[ $b="t" ] && sudo mount /dev/sbb /media/bb # Not direct paths, like here.
[ $c="t" ] && sudo mount /dev/sbc /media/bcTo me, this code is redundant. Is there any more efficient/better way to do it ?
Which language should I use for this task?
Solution
Since you're using bash (I assume a recent version of bash), you can use some advanced features, like associative arrays and indirect variables
Note that the
#!/bin/bash
# If no argument is passed, act on all partitions.
if (( $# == 0 )); then
a=t b=t c=t
else
for arg; do
if [[ $arg == a|b|c ]]; then
declare $arg=t
else
echo "ignoring argument '$arg'"
fi
done
fi
declare -A uuids=( [a]=1234 [b]=3456 [c]=5678 )
for dest in a b c; do
if [[ ${!dest} == t ]]; then
sudo mount /dev/sb$dest "${uuids[$dest]}"
fi
doneNote that the
[ command acts differently when given different numbers of arguments. With just a single argument (such as [ $a="t" ]), you'll get a success exit status if the argument is not empty (and the string "$a=t" is not empty no matter the value of $a). You have to put spaces between all the operators and operands for [ and test and [[.Code Snippets
#!/bin/bash
# If no argument is passed, act on all partitions.
if (( $# == 0 )); then
a=t b=t c=t
else
for arg; do
if [[ $arg == a|b|c ]]; then
declare $arg=t
else
echo "ignoring argument '$arg'"
fi
done
fi
declare -A uuids=( [a]=1234 [b]=3456 [c]=5678 )
for dest in a b c; do
if [[ ${!dest} == t ]]; then
sudo mount /dev/sb$dest "${uuids[$dest]}"
fi
doneContext
StackExchange Code Review Q#63188, answer score: 6
Revisions (0)
No revisions yet.