0

im trying to make a script for a school project but i can't solve this problem. I will leave my code with comments, i hope you can understand my problem. Thanks in advance.

#!/bin/bash

directory=$HOME/.impressora
imp=0

mkdir -p $directory
#check if $HOME/.impressora exists, if not, create it

if [ ! -f "$directory/.*" ]
# if there is no ".something" file in "$HOME/.impressora"
then echo "" > $directory/.200
# then create a file called ".200" in "$HOME/.impressora"
fi

creditos=$(echo  "$directory/*" | cut -f 3 -d '.')
# here is my problem, i want the value of the variable "creditos" to be what comes after the "." on the file in "$HOME/.impressora" , so, in # this case, the file in "$HOME/.impressora" is called ".200" , so the objective is to make "creditos" = 200
# I hope you can help me figure out whats wrong!

if [ $1 = "lp" ] 
# if the first variable is "lp" then.
then
    if [ -d $directory ] && [ $creditos > 0 ]
    #if "$/HOME/.impressora" exists and $creditos > 0
    then 
        echo "" > $directory/lp-$imp
        # create an empty file called "lp-$imp" (in wich $imp will be a number)
        ((imp++))
        $cred=$creditos
        ((cred--))
        mv $directory/.$creditos $directory/.$cred
        # the objective here is to change the name of the file in "$HOME/.impressora" , so in this case it would go from ".200" to ".199"
    # and so on and so on. 
    else 
        echo "Diretorio inexistente ou creditos insuficientes"
    fi

UPDATE:

I just found myself a solution for my problem!

As the file as no name (because it starts with a dot) it's automatically the first file to appear at your directory is that one. So first you need to "ls -a" your dir. Next you need to jump the two "files" that appear which are the:

.

and

..

So, you do the "head -3" command so you can select the 3 first lines (files) of the folder. Next you need to select the last one of those 3 so you pipe it again and do the "tail -1"

Finally you need to remove the dot in the .200 file so you can save only the value to the var, to do this you have to pipe "cut -f2 -d".""

Basicly you need to replace the

creditos=$(echo $directory/.* | cut -c7-)

with

creditos=$(ls -a $directory | head -3 | tail -1 | cut -f2 -d".")

1 Answers1

0

$directory/* expands to only non-hidden files by default.

If you do shopt -s dotglob, $directory/* will match all files (including . and ..). You will want to undo it with shopt -u dotglob after.

$directory/.*, you will only match the hidden files (regardless of dotglob). If you assume there is nothing else in that directory, echo .* | cut -c7- should give you 200.

Amadan
  • 191,408
  • 23
  • 240
  • 301