Questions with exercise in Shellscript

0

I would like some help to resolve these exercises:

In the ex4.1.sh script, add the option to enter the word and filename directly from the command line like this:

$  ./ex4.1.sh  <palavra>  <arquivo> 

In script ex4.1.sh the output of the "grep" command is displayed on the screen. Change the script so that this result does not appear on the screen. Write a script that tests whether the value passed as day, month, and year parameter is a valid date.

The script in this case is from here:

#!/bin/bash
# ex4.1.sh - teste de desvio
# Script para verificacao de estrutura de desvio
# localiza uma string em um arquivo
echo -n "Digite a palavra a ser localizada: "
read palavra
echo -n "Qual o arquivo a procurar?: "
read arquivo
if grep $palavra $arquivo
 then
   echo "$palavra encontrada no arquivo $arquivo"
   sleep 5
 else
   echo "$palavra não encontrada no arquivo $arquivo"
   sleep 5
 fi

Hello colleague fedorqui I was able to solve this example you gave, the problem is that I was doing it as if it were a script with the code entered in gedit when it was to type directly at the linux command prompt, there is the result

$ date -d "holaaa" 2 > / dev / null & echo "Correct" || echo "Incorrect"

Incorrect

$ date -d "06 Dec 2017" 2 > / dev / null & echo "Correct" || echo "Incorrect"

Wed Dec 6 00:00:00 AMT 2017

Correct

    
asked by anonymous 28.03.2017 / 15:03

1 answer

2
  

In the ex4.1.sh script, add the option to enter the word and filename directly from the command line like this:

Get the values with $1 , $2 ...:

palavra=$1
arquivo=$2

So, $palavra contains the first and $arquivo the second:

With script.sh :

#!/bin/bash

palavra=$1
arquivo=$2
echo "palavra: $palavra. arquivo: $arquivo"

I'm going to run:

$ ./script.sh "uma palavra" "hola.txt"
palavra: uma palavra. arquivo: hola.txt
  

Change the script so that this result does not appear on the screen

Get the results in a variable:

res=$(grep "$palavra" "$arquivo")
  

Write a script that tests whether the value passed as day, month, and year parameter is a valid date.

Use date -d"<fecha>" :

$ date -d"holaaa" && echo "correcto" || echo "incorreto"
date: invalid date ‘holaaa’
incorreto
$ date -d"23 Mar 2017" && echo "correcto" || echo "incorreto"
Thu Mar 23 00:00:00 CET 2017
correcto
    
28.03.2017 / 15:30