0

I don't know what I am doing and could use some assistance with my script.

$ ./mysql.sh LOCALIP 'SELECT LOCALIP FROM Host'

mysql.sh

#!/bin/bash
source $PWD/data/login

mapfile -t "$1" < <(mysql -N ""$DB"" -h""$HOST"" -u""$USER"" -p""$PASS"" -se "$2")

echo ${$1[0]}
echo ${$1[1]}
echo ${$1[2]}
echo ${$1[3]}

fi

Output

[シ]owner@gwpi ~/scriptdir $./mysql.sh LOCALIP 'SELECT LOCALIP FROM Host'
./mysql.sh: line 10: ${$1[0]}: bad substitution

  • Might have found an answer to my question elsewhere and here it is: ```eval "echo \${$1[0]}"``` – Cody Millard Sep 22 '22 at 02:35
  • 1
    Don't double the double-quotes. In `""$DB""`, each pair of double-quotes creates a zero-length quoted section, which has no effect at all on the argument(s) passed to the `mysql` command (unless `$DB` evaluates to the null string, in which case they prevent it from just vanishing from the argument list). Since `$DB` isn't in double-quotes, it's subject to all word-splitting and wildcard expansion, neither of which you want. Also, you can't nest variable expansions like `${$1[0]}` (what are you trying to do there?). [shellcheck.net](https://www.shellcheck.net) would've spotted these; use it! – Gordon Davisson Sep 22 '22 at 02:50
  • Also, `$HOST` and `$USER` (and many other all-caps variable names) have special meanings in the shell; unless you specifically want those special meanings, it's safer to user lower- or mixed-case variable names for a script's internal variables. – Gordon Davisson Sep 22 '22 at 02:51
  • @GordonDavisson I am creating for fun a self hosted system monitoring service. My various boxes would run a script that uploads some basic information like VPN status, externalip about themselves to my mysql server and that information would be displayed about each upon logging into any of them in a motd. – Cody Millard Sep 22 '22 at 03:23

1 Answers1

0

Simply replace the varible $1 with var here.It works.

$ mapfile -t var < <(mysql -N ""$DB"" -h""$HOST"" -u""$USER"" -p""$PASS"" -se "$2")
$ echo" ${var[@]}"

Original script has two problems.

  • You cannot change $1 arg in this way.Right style refers to this
  • should be better using more meaningful variables than $1
mariolu
  • 624
  • 8
  • 17
  • might need some explanations about the changes. – Raptor Sep 22 '22 at 03:07
  • I cannot get the code to format correctly to post all of it but you can run a script like `./script.sh test` that contains `echo $1`, the result is test. – Cody Millard Sep 22 '22 at 03:35
  • Here is an example of passing the $1 (and $2, $3) arguments along in shell scripts as modifiers/switches. I don't know the proper terminology for this. https://pastebin.com/vuT32H5Y – Cody Millard Sep 22 '22 at 03:57