0

I'm try to run a script that figures out the paths based on the hostname: e.g. if hostname returns computer1 I would like to run path/to/Computer1.py (where path/to is a path that will always be the same).

The path part I figured I could use a variable to store it, then recall and concatenate later. I looked up now to convert a string to title case and this seems to work:

echo "computer1.py" | awk '{printf("%s%s\n",toupper(substr($0,1,1)),substr($0,2))}'

I'm fairly new to bash and currently I'm getting stuck on how I should concatenate these components ( path to script, script name based on hostname) and execute them.

1 Answer 1

3

Bash version 4 introduced built-in case-modification operators ^ and , operators, making it possible to avoid external programs like awk for such simple string manipulations if you have a recent version of the bash shell. In particular, if

name=$(hostname)

and

path="path/to/"

then

"${path}${name^}"

should concatenate the strings, with the first letter of name upper-cased. See the Parameter Expansion section of the bash manual page man bash.

4
  • That is very helpful(+1). Unfortunately I haven't managed to get the upper-cased part working. I get bad substitution. For example ``` n='computer1'``` then calling ${n^} prints bad substitution. What am I missing ? Thank you Commented Aug 31, 2015 at 7:41
  • For now I did something like this: $('/path/to/'$(hostname | awk '{printf("%s%s.py",toupper(substr($0,1,1)),substr($0,2))}')) and this worked, but doesn't look as elegant as what you're proposing. Looking forward to learn how to use that correctly Commented Aug 31, 2015 at 8:54
  • @GeorgeProfenza what is your platform and bash version (bash --version)? IIRC the built-in toupper (^) and tolower (,) operators were introduced in Bash 4 - perhaps your shell doesn't have them. BTW don't feel obligated to accept an answer if it doesn't work for you. Commented Aug 31, 2015 at 11:37
  • I tested initially on osx running GNU bash, version 3.2.53(1)-release-(x86_64-apple-darwin14), however script is intended to un on a Raspberry PI 2 running raspian. I don't have access to one right now, so can't provide the bash version at the moment. It looks like your answer should've worked and it looks elegant which is why I accepted it. You are right, but perhaps just mention your solution runs on Bash 4 which might help people looking at your answer in the future (and skipping your comments) Commented Aug 31, 2015 at 13:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .