0

I try to understand why the following code fails. First I invoke a bash-function with

smb_read $SMB_FILE $SMB_CONF

The function is simple

function smb_read {
  2="$(cat $1)"
  case $? in
    0) ;;
    *) return 1 ;;
  esac
}

The result is

func.sh: line 52: 2=[global]
workgroup = smb
security = user
...
public = no
writeable = no
guest ok = no
create mask = 0600
directory mask = 0700: No such file or directory

Why is that?

user1587451
  • 978
  • 3
  • 15
  • 30
  • Numbers aren't legal variable names. It **is** possible to change the value of `$2`, but only if rewriting your function's whole argument list; you can't assign to it directly. – Charles Duffy Apr 05 '19 at 16:46
  • ...which is to say, this has nothing to do with the reading-a-file, and everything to do with where you're trying to store the result; you'd have the same problem with `2=hello`. – Charles Duffy Apr 05 '19 at 16:47
  • ...that said, is your actual goal to perform an indirect assignment (so you want `SMB_CONF` to be the variable name where the contents of `SMB_FILE` are stored)? For that, see [BashFAQ #6](https://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables). – Charles Duffy Apr 05 '19 at 16:48
  • `smb_read() { printf -v "$2" %s "$(<"$1")"; }; smb_read "$SMB_FILE" SMB_CONF` should suffice in that case. Note that `$2` is being passed the literal variable name, not the variable's contents. – Charles Duffy Apr 05 '19 at 16:49
  • BTW, note that all-caps variable names are used for variables meaningful to the shell and operating system, while lowercase names are reserved for application use. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html (specifically, the paragraph w/ the sentence *"The name space of environment variable names containing lowercase letters is reserved for applications"*), keeping in mind that shell and environment variables share a namespace (assigning a shell variable overwrites any like-named environment variable). – Charles Duffy Apr 05 '19 at 16:50

0 Answers0