0

This is a very simple question. It requires a very simple answer. I'd rather not be referred to a book-length, overly general answer.

I want to replace all occurrences of & with + and put the value back into $targetDir

targetDir="&&&&&"
echo $targetDir # &&&&&

$targetDir=$targetDir | tr '&' '+' # *How do I actually make this happen?

echo $targetDir # +++++
Craig Wilcox
  • 1,577
  • 1
  • 12
  • 23
  • `targetDir=$(echo "$targetDir" | tr ...)` -- note no `$` on the left-hand side; this isn't perl. `$` is an expansion operator, not part of the actual variable name. – Charles Duffy Jun 30 '23 at 15:08
  • 1
    That said, `targetDir=${targetDir//'&'/+}` is the faster/more efficient way to write this operation. – Charles Duffy Jun 30 '23 at 15:09
  • And use `echo "$targetDir"`, not `echo $targetDir` -- see [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Jun 30 '23 at 15:10
  • (even better would be replacing `echo "$targetDir"` with `printf '%s\n' "$targetDir"`; that way it'll work correctly in corner cases like `targetDir=-n`, and regardless of shell configuration when the directory name contains a backslash literal; see [Why is printf better than echo?](https://unix.stackexchange.com/questions/65803) on [unix.se]; note in particular the parts talking about the `xpg_echo` flag in bash, and see the APPLICATION USAGE notes in the [POSIX `echo` standard](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html)). – Charles Duffy Jun 30 '23 at 15:13
  • @CharlesDuffy in bash you don't need echo, just `targetDir=$(<<<$targetDir tr ...)` – phuclv Jun 30 '23 at 15:41
  • @phuclv, indeed. That said, with all but the very latest versions of bash, heredocs and herestrings create a temporary file; that might not be desirable. – Charles Duffy Jun 30 '23 at 16:11
  • @phuclv, right, that's why I said "all but the very latest versions". – Charles Duffy Jun 30 '23 at 16:33

0 Answers0