2

Currently, I am struggling getting 2 codes working in my bash script. They both work separately, but once they are both in the code, they don't.

var=$(cat /sys/block/vda/queue/rotational 2>/dev/null || cat /sys/block/sda/queue/rotational 2>/dev/null)
dtype='nil'
if [ $var = 0 ]; then
dtype=' SSD '
elif [ $var = 1 ]; then
        dtype=' HDD '
fi


var1=$(lsmod | grep kvm | awk 'NR==1{print $3}'  2>/dev/null)
vtype = 'no'
if [ $var1 = 0 ]; then
        vtype=' no '
else
    vtype = 'yes'
fi

printf '$dtype' '$vtype'
echo $dtype $vtype

First variable var is supposed to hold the value of rotational file. Asks 0 is for SSD and 1 is for HDD.

The second variable var1 checks if virtualization is present in your machine. If the number it holds is 0, then vtype is set to no, if its something else, then vtype is set to yes. These commands work perfectly, if i do them on different code files. But i need them both together. Any suggestions?

5
  • 4
    What is not working – Inian Mar 26 '18 at 7:48
  • 3
    The printf command at the end is wrong. The first argument should be a format string. Try printf '%s %s\n' "$dtype" "$vtype" (note also the choice of quotes here). – Kusalananda Mar 26 '18 at 7:49
  • 5
    = must no be surrounded by space (when assigning that is) – Archemar Mar 26 '18 at 7:49
  • 3
    See shellcheck.net – Kusalananda Mar 26 '18 at 7:50
  • 2
    Thanks @Kusalananda your printf worked better and the shellcheck helped also, will use it more now as i did not know of it before. – TheSebM8 Mar 26 '18 at 8:01
12

There are four main issues in this script:

  1. The #!-line at the top is missing. As far as I can see, this can be #!/bin/sh.

  2. Variable expansions are unquoted. Use double quotes to avoid word-splitting and filename globbing. For example, if [ "$var" = 0 ]. Here you may also choose to use -eq in place of = since you're doing an arithmetic test.

  3. Assignments must not have spaces around =.

  4. The first argument of printf should be a format string, for example printf '%s %s\n' "$dtype" "$vtype".

These things may be found using the ShellCheck site.

There is also a minor inefficiency:

lsmod | grep kvm | awk 'NR==1{print $3}'  2>/dev/null

could be written, almost equivalently,

lsmod | awk '/kvm/ { print $3; exit }'

I'm not sure why you put spaces in the values of some of the variables, e.g. dtype=' HDD '.

1
  • 1
    Note that a missing #! is the POSIX way to write POSIX scripts (though I'd tend to agree using #! /bin/sh - is preferable, at least on systems where /bin/sh is a POSIX shell) – Stéphane Chazelas Mar 26 '18 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.