I
I
ivan_kholodov2021-08-23 14:53:28
bash
ivan_kholodov, 2021-08-23 14:53:28

How to get parse and return string from bash function?

Good afternoon!
Please advise how to write a function in bashso that it takes one argument, and inside you can parse this argument (string) and return a number from it

к примеру:
function myFunc {
  return +arg.split('-', 2)
}

then call it already in the block ifunder the appropriate condition myFunc $1

, but bashit doesn’t work like that and I can’t start this business.

code in if
elif ; then
  ...прочий конфиг --mark myFunc $2


and then I run this command from the command line behind the flag -- p-4
and I need to get 4-ku to process it further.

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xotkot, 2021-08-23
@ivan_kholodov

oh, and you explain confusingly, I meditated for half an hour before roughly understanding what you need, although I’m not sure even that

how to write a function in bash so that it takes one argument, and inside you can parse this argument (string) and return a number from it

foo() {
  foo_arg1="$1"
  echo "$foo_arg1" | awk -F- '/^p-{1,}$/{printf $2}'
}
foo p-4 # вернет 4

made a regular expression with a check for a number after p-
then call already in the if block with the appropriate condition myFunc $1
code in if
elif ; then
  ...прочий конфиг --mark myFunc $2

firstly, 'p-"${2}"' will be exactly the string p-"${2}" and not p-whatever , since it is framed in single quotes here, it would be more correct to write the condition like this: that is, it will approximately be such a script:

#!/usr/bin/env bash

arg1="$1"
arg2="$2"

foo() {
  foo_arg1="$1"
  echo "$foo_arg1" | awk -F- '/^p-{1,}$/{printf $2}'
}

if ; then
  echo --mark $(foo $arg1)
fi
exit

let's call the script 0.sh , then
./0.sh p-4 4
--mark 4
./0.sh p-4 5 # ничего не выведет так как p-4 неравно p-5

J
jcmvbkbc, 2021-08-23
@jcmvbkbc

I run this command from the command line after the --p-4 flag
and I need to get 4-ku to process it further.

something like this?:
#! /bin/bash

foo()
{
    RES="${1#p-}";
}

foo "$1"
echo "$RES"

nothing is clear from the explanation.

X
xibir, 2021-08-23
@xibir

parse()
{
   # do something
   echo $1
}

a=`parse test1 test2`
echo $a

H
hint000, 2021-08-23
@hint000

echo $1 | awk -F- '$1=="p"{print $2}'
if $1 is "p-4" it will output 4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question