0

Having an odd time with a bit of code. I'm sure it's a simple fix but am unsure what that is.

#!/bin/bash
read -p 'Enter file name: ' fileName
exe=${fileName: 0: -2}
gcc $fileName -o $exe
chmod a+x $exe
./$exe

I found out it is not working at the second line but when I run it on it's works fine and as expect. I suspect its an issue with running a script within a script but am not sure how I might fix it

adjoth
  • 1
  • 2
  • `I found out it is not working at the second line but when I run it on it's works fine` I don't get it, so it doesn't work when you don't run it, but works when you run it? – KamilCuk Aug 12 '20 at 17:54
  • Are you sure you're running the script with `bash`? Does it begin with `#!/bin/bash`? – Barmar Aug 12 '20 at 18:03
  • So if I run each line one by one it works. However if I run it as a script the second line will fail to store anything (like the data is nothing or null). I do not have the #! /bin/bash/ but it didn't change anything after being added as the exe variable is still blank when I echo it out. – adjoth Aug 12 '20 at 19:34
  • How is it actually being invoked? Having `#!/bin/bash` at the top won't help if you're running it with `sh yourscript`. – Charles Duffy Sep 02 '20 at 01:56
  • BTW, quote your expansions. `gcc "$fileName" -o "$exec"`, `cmod a+x "$exe"`, `"./$exe"`, etc; otherwise you can have surprising behavior when your filenames have spaces or glob characters or your `IFS` is set to a non-default value. – Charles Duffy Sep 02 '20 at 02:00
  • (also, if `/bin/bash` is a much older version of bash than the one that `/usr/bin/env bash` finds from searching your PATH, it might not be the appropriate shebang either; put `echo "Bash version: ${BASH_VERSION:-shell is not bash}" >&2` in your script to see which version of bash it's using, if the shell that runs it is in fact bash at all). – Charles Duffy Sep 02 '20 at 02:02

0 Answers0