Seeking advice from teachers on a shell script issue

Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: 请教各位老师1个shell 脚本的问题

| username: Raymond

I have a question for the teachers about a shell problem.
I defined a function ab, which is supposed to receive a parameter to execute the tiup cluster exec command. However, the awk '{print $1}' inside the command treats $1 as the function’s parameter, which is not the expected behavior. Is there any way to avoid this?

ab(){
  name="$1"
  echo $name
  ck=`tiup cluster exec $name --command "hostname -I | awk '{print \$1}'"`
}
ab "test"
| username: tidb菜鸟一只 | Original post link

ab(){ 
    name="$1"
    echo "$name"
    ck=$(tiup cluster exec "$name" --command "hostname -I | awk '{print $1}'")
    echo "$ck"
}
ab "test"
| username: redgame | Original post link

ab(){
  name="$1"
  echo "$name"
  ck="tiup cluster exec $name --command \"hostname -I|awk '{print \$1}'\""
}
ab "test"
| username: Raymond | Original post link

This method won’t work.

| username: Raymond | Original post link

This method doesn’t work either.

| username: 我是咖啡哥 | Original post link

Tested and works

#!/bin/bash

ab(){
name=$1
echo $name
ck=`tiup cluster exec $name --command 'hostname -I|awk "{print $1}"'`
echo $ck
}
ab test
| username: 我是咖啡哥 | Original post link

Pay attention to the details.
Using double quotes inside ensures that $1 will not be converted.

| username: Raymond | Original post link

Sure, thank you Coffee Brother.

| username: Jellybean | Original post link

Brother Coffee :+1: