0

I am trying to get this simple function working:

p4edit(){
    p4 edit ${$1:25}
}

I read the other popular bad substitution question on SO and it did not seem to help me or be related to my problem. What am I doing wrong here? I want to cut off the first 25 characters of the argument provided to my function.

I have noticed a simple echo ${"test":3} fails the same way, but this succeeds:

test="test"
echo ${test:3}

I am just running this in a bash instance.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

2 Answers2

2

Why two times a $ ?

p4edit(){
  echo ${1:25}
}

works fine for me. String functions in bash are a bit tricky, since they are not really consistent. But ${} already defines, that you are looking for a variable. So only submit the name to it. There are some stringfunctions with ${#var} but as far as I know, there is never a $ inside a ${}

Doktor OSwaldo
  • 5,732
  • 20
  • 41
  • No, there is a case where `$` is inside. I fixed the error by adding the second `$` here: `for str in ${$(someVar)//;/ } ; do` (but a result is not that I expected). – CoolMind Mar 02 '23 at 14:47
2

You have too much money! (too many dollar signs). Use:

p4edit(){
    p4 edit ${1:25}
}

To extract the 25th-and-onwards characters from $1.

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38