MrZ
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Kurs Administrowania Systemami Linux Lista 1 ## Zad 1. ### Narzędzia cloc i sloccount #### cloc (Count Lines of Code) cloc to narzędzie, które analizuje źródła plików (lub katalogów) i wyświetla liczbę linii kodu, komentarzy i pustych linii podzielonych na różne języki programowania. Jest to przydatne do oceny wielkości projektu lub wkładu w projekt. cloc counts blank lines, comment lines, and physical lines of source code in many programming languages. Given two versions of a code base, cloc can compute differences in blank, comment, and source lines. It is written entirely in Perl #### sloccount (Source Lines of Code Count) sloccount również służy do liczenia linii kodu w wielu językach programowania. Poza liczeniem linii kodu, sloccount może szacować koszty projektu (np. na podstawie modelu COCOMO), prezentując koszt w osobolatach oraz ekwiwalent kosztów w dolarach amerykańskich. sloccount counts the physical source lines of code (SLOC) contained in descendants of the specified set of directories. It automatically determines which files are source code files, and it automatically determines the computer language used in each file. ```bash= #!/bin/bash ARCHIVE_PATH="/home/user/linuxes/" versions=("0.99.15j-1993" "1.1.95-1995" "2.0.27-1997" "2.2.0-1999" "2.4.0-2001" "2.4.20-2003" "2.6.10-2005" "2.6.19-2007" "2.6.28-2009" "2.6.37-2011" "3.7.1-2013" "3.18-2015" "4.9-2017" "4.20-2019" "5.10-2021" "5.15-2023") for version in "${versions[@]}" do echo "Analizuję wersję $version..." ARCHIVE="$ARCHIVE_PATH/linux-$version.tar.xz" if [ -f "$ARCHIVE" ]; then DIRECTORY="$ARCHIVE_PATH/linux-$version" mkdir -p "$DIRECTORY" tar -xJf "$ARCHIVE" -C "$DIRECTORY" if [ -d "$DIRECTORY" ]; then # Utwórz katalog na wyniki, jeśli nie istnieje mkdir -p "$DIRECTORY/results" # Analiza cloc cloc "$DIRECTORY" --out="$DIRECTORY/results/cloc_results_$version.txt" # Analiza sloccount sloccount "$DIRECTORY" > "$DIRECTORY/results/sloccount_results_$version.txt" else echo "Nie udało się utworzyć katalogu: $DIRECTORY" fi else echo "Archiwum $ARCHIVE nie istnieje." fi done ``` ```python import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import os import re results_path = "/home/user/linuxes/" versions = [] person_years = [] person_months = [] total_costs = [] for version in os.listdir(results_path): sloccount_file = os.path.join(results_path, version, "results", "sloccount_results_" + version.lstrip("linux-") + ".txt") if os.path.isfile(sloccount_file): with open(sloccount_file, 'r') as file: data = file.read() total_cost_match = re.search(r'Total Estimated Cost to Develop\s+= \$ ([\d,]+)', data) data = data.replace(",", "") person_years_match = re.search(r'Development Effort Estimate Person-Years \(Person-Months\) = ([\d.]+) \(([\d.]+)\)', data) if person_years_match and total_cost_match: versions.append(f'{version.split("-")[2]}-{version.split("-")[1]}') person_years.append(float(person_years_match.group(1))) person_months.append(float(person_years_match.group(2))) total_costs.append(int(total_cost_match.group(1).replace(',', ''))) df = pd.DataFrame({ 'Version': versions, 'Person-Years': person_years, 'Person-Months': person_months, 'Total Cost ($)': total_costs }) df.sort_values(by='Version', inplace=True) fig, ax1 = plt.subplots(figsize=(28, 12)) color = 'tab:red' ax1.set_xlabel('Version') ax1.set_ylabel('Person-Years', color=color) line1, = ax1.plot(df['Version'], df['Person-Years'], color=color, label='Person-Years', marker='o') ax1.tick_params(axis='y', labelcolor=color) plt.xticks(rotation=45) # Dodajemy adnotacje do wykresu dla 'Person-Years' for i, (py, cost) in enumerate(zip(df['Person-Years'], df['Total Cost ($)'])): ax1.annotate(f'{py:.2f}\n$ {cost:,.0f}', (i, py), textcoords="offset points", xytext=(0,10), ha='center', color=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('Total Cost ($)', color=color) line2, = ax2.plot(df['Version'], df['Total Cost ($)'], color=color, label='Total Cost ($)', marker='x') ax2.tick_params(axis='y', labelcolor=color) # Formatowanie osi Y dla większej dokładności ax2.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f'${x:,.0f}')) fig.tight_layout() plt.title('Development Effort and Total Cost over Different Versions of Linux Kernel') # Poprawione dodawanie legendy z uwzględnieniem obu linii plt.legend([line1, line2], ['Person-Years', 'Total Cost ($)'], loc="upper left") plt.show() ``` ![Figure_1](https://hackmd.io/_uploads/HknyGqGTp.png) ## Zad 2. - gedit ~/.bashrc - alias ll='ls -lAFbhv --color=always | less -XER' #### LS: -l, list file's inode index number -A, --almost-all do not list implied . and .. -F, --classify append indicator (one of */=>@|) to entries -b, --escape print C-style escapes for nongraphic characters -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc. -v natural sort of (version) numbers within text --color[=WHEN] colorize the output; WHEN can be 'always' (default if omitted), 'auto', or 'never'; more info below #### LESS: -E or --QUIT-AT-EOF Causes less to automatically exit the first time it reaches end-of-file. -R or --RAW-CONTROL-CHARS displays escape characters, but only ANSI ones. Doesn't make line errors like -r. -X or --no-init Disables sending the termcap initialization and deinitialization strings to the terminal. This is sometimes desirable if the deinitialization string does something unnecessary, like clearing the screen. - alias gentmp='echo -n "tmp-"; date +'%Y%m%d%H%M%S'' - alias genpwd='cat /dev/urandom | tr -dc '3-9A-HJ-NP-Z' | head -c 5 ; echo' ## Zad 3. grep - pattern matching ### ciekawsze opcje: -E pozwala na podawanie regex'ów jako pattern -c zlicza wystąpienia patternu -i case insensitive search -R rekursywnie sprawdzaj wszystkie katalogi i podkatalogi w poszukiwaniu patternu -F Interpret PATTERNS as fixed strings, not regular expressions. ### basic concepts: - A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey". - Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gray|grey and gr(a|e)y are equivalent patterns which both describe the set of "gray" or "grey". - ? The question mark indicates zero or one occurrences of the preceding element. For example, colou?r matches both "color" and "colour". - \* The asterisk indicates zero or more occurrences of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on. - \+ The plus sign indicates one or more occurrences of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac". - {n} The preceding item is matched exactly n times. - {min,} The preceding item is matched min or more times. - {,max} The preceding item is matched up to max times. - {min,max} The preceding item is matched at least min times, but not more than max times. - Wildcard: The wildcard . matches any character. For example: - a.b matches any string that contains an "a", and then any character and then "b". - a.*b matches any string that contains an "a", and then the character "b" at some later point. ## Zad. 4 find - search for files in a directory hierarchy ### ciekawsze opcje: -name pozwala podać pattern dla szukanego pliku -iname case insensitive -name -P don't follow symlinks -> default behavior -L follow symlinks -maxdepth maks. głębokość szukania -o or, przykład: find ~ ( -iname 'jpeg' -o -iname 'jpg' ), szukaj plików .jpg i .jpeg -perm szukanie po uprawnieniach plików -type specyfikacja czego szukamy -type d to katalogi, -type f pliki itp. -regex pozwala uzywac regexa ## Zad. 5 Bazowy rename w ubuntu to nie ten perlowy. Aby zainstlaować perlowy trzeba zrobić: - sudo cpan - install File::Rename Potem man rename pokazuje już perlowego rename'a. Przykład: rename -n 's/[.]png$/.txt/' *.png Zamienia rozszerzenia podanych plików z .png na .txt s/ -> Search and replace is performed using s/regex/replacement/modifiers. https://perldoc.perl.org/perlrequick#Search-and-replace ## Zad. 6 Listowanie zainstalowanych pakietów - apt list --installed ![image](https://hackmd.io/_uploads/HJW2Ytz66.png) Listę zainstalowanych pakietów, które nie posiadają własnego podkatalogu w /usr/share/doc/. ```bash= - apt list --installed | sed 's=/.\+==g' 2> /dev/null | while read x; do if [ ! -d /usr/share/doc/$x ]; then echo $x; fi; done ``` Listę podkatalogów katalogu /usr/share/doc/, których nazwy nie są nazwami żadnego zainsta- lowanego pakietu. Przy każdym z takich podkatalogów wypisz nazwę pakietu, który jest jego właścicielem. Bierzemy wszystkie katalogi z /usr/share/doc i po kolei czy są w liście zainstalowanych pakietów, jeśli tak to patrzymy kto jest ich ownerem przy pomocy dpkg -S. ```bash= - ls /usr/share/doc | while read x; do if [ $(apt list --installed 2> /dev/null | sed 's=/.\+==g' 2> /dev/null | grep -w "$x" | wc -l) -eq 1 ]; then echo $(dpkg -S "/usr/share/doc/$x"); fi; done ``` Old: ```bash= - ls /usr/share/doc | while read x; do dir=$(basename "$x"); if [ $(apt list --installed 2> /dev/null | sed 's=/.\+==g' 2> /dev/null | grep -w "$dir" | wc -l) -eq 1 ]; then echo $(dpkg -S "/usr/share/doc/$dir"); fi; done ``` Listę pakietów posiadających własny podkatalog w katalogu /usr/share/doc/, który jednak nie zawiera pliku changelog.Debian.gz. Bierzemy listę wszystkich zainstalowanych pakietów i po kolei patrzymy czy istnieje taki katalog w odpowiednim folderze. Jeśli istnieje to patrzymy czy znajduję się ten plik w nim. ```bash= apt list --installed | sed 's=/.\+==g' 2> /dev/null | while read x; do if [ -d /usr/share/doc/$x ]; then if [ $(find /usr/share/doc/$x -name changelog.Debian.gz 2> /dev/null | wc -l) -gt 0 ]; then echo $x; fi fi done ``` Listę pakietów posiadających własny plik changelog.Debian.gz, który zawiera tylko jeden wpis (zwykle Initial release). ```bash= apt list --installed | sed 's=/.\+==g' 2> /dev/null | while read x; do if [ -d /usr/share/doc/$x ]; then if [ $(find /usr/share/doc/$x -name changelog.Debian.gz 2> /dev/null | wc -l) -gt 0 ]; then entry=$(zcat "/usr/share/doc/$x/changelog.Debian.gz"); if [ $(wc -l $entry) -eq 1 ]; then echo $x; fi fi fi done ``` ## Zad. 7 - sudo find /lib /usr/lib /usr/local/lib -type f -name ".*\.so\(\.[0-9]\+\)\?$" - sudo find / -type l -lname ".*\.so\(\.[0-9]\+\)\?$" - sudo find / -type f -name ".*\.so\(\.[0-9]\+\)\?$" | du -ch * | tail -1 - ## Zad. 8 ### 1. Lista wszystkich nazw języków, dla których istnieje plik MO co najmniej jednego programu ```bash find /usr/share/locale/ -type f -name "*.mo" | sed -r 's|/usr/share/locale/(.*)/LC_MESSAGES.*|\1|' | sort -u ``` Ten fragment kodu wykonuje następujące czynności: - `find /usr/share/locale/ -type f -name "*.mo"`: wyszukuje wszystkie pliki `.mo` w katalogu `/usr/share/locale/`. - `sed -r 's|/usr/share/locale/(.*)/LC_MESSAGES.*|\1|'`: używa `sed` do przetworzenia ścieżek plików, wyodrębniając część odpowiadającą nazwie języka. - `sort -u`: sortuje wyniki i usuwa duplikaty, pozostawiając unikalne nazwy języków. ### 2. Lista wszystkich nazw języków, dla których istnieją komunikaty programu dpkg ```bash find /usr/share/locale/ -type f -path "*/LC_MESSAGES/dpkg.mo" | sed -r 's|/usr/share/locale/(.*)/LC_MESSAGES/dpkg.mo|\1|' | sort -u ``` Zmieniamy tutaj fragment wyszukiwania `find` na `-path "*/LC_MESSAGES/dpkg.mo"` aby znaleźć pliki `dpkg.mo` w katalogach `LC_MESSAGES` i następnie wyodrębniamy nazwy języków. ### 3. Lista wszystkich programów posiadających komunikaty w języku pl ```bash find /usr/share/locale/pl/LC_MESSAGES/ -type f -name "*.mo" | sed -r 's|/usr/share/locale/pl/LC_MESSAGES/(.*)\.mo|\1|' | sort -u ``` Tutaj koncentrujemy się na katalogu dla języka polskiego (`pl`), wyszukując pliki `.mo` i wyodrębniając nazwy programów z nazw plików. ### 4. Lista wszystkich nazw języków, dla których istnieje co najmniej jedna strona dokumentacji w danym rozdziale Dla każdego z ośmiu rozdziałów (man1–man8): ```bash for i in {1..8}; do echo "Rozdział man$i:" find /usr/share/man/ -type f -path "*man$i/*.[1-8]" | sed -r 's|/usr/share/man/(.*)/man'"$i"'/.*|\1|' | sort -u done ``` ### 5. Lista wszystkich stron podręcznika w języku pl dla każdego z ośmiu rozdziałów Dla każdego rozdziału: ```bash for i in {1..8}; do echo "Rozdział man$i w języku pl:" find /usr/share/man/pl/man$i/ -type f -name "*.$i" | xargs -n1 basename | sort -u done ``` W powyższych poleceniach używamy pętli `for` do iteracji przez każdy z rozdziałów podręcznika, używamy `find` do wyszukania odpowiednich plików, a następnie przetwarzamy ścieżki plików, aby wyodrębnić potrzebne informacje. ## Zad. 10 Polecenie służące do edytowania strumienia tekstu (plików tekstowych lub inputów z pipeline'ów) Przykład użycia: sed 's/old_string/new_string/' filename.txt Znajdź pierwsze wystąpienie stringa old_string i zamień je na new_string w pliku filename.txt dodanie flagi g spowoduje zamianę wszystkich wystąpień, a nie tylko pierwszego: sed 's/old_string/new_string/g' filename.txt Zamiast g można wpisać liczbę, np. 2 wtedy zamieni tylko 2 wystąpienia. Flaga i ignoruje wielkość liter w patternie. sed 'i,j edytuje plik w liniach od i do j. sed '5d' filename.txt usuwa linie i w pliku filename.txt Analogicznie sed 5,10d usuwa linie od 5 do 10 sed 'i,$d' usuwa wszystkie linie od linii i. ## Zad. 11 ```bash= #!/bin/bash seq="$1" prev_seq="" length=${#seq} iteration=0 while [ "$seq" != "$prev_seq" ]; do prev_seq="$seq" echo "Iteration: $iteration, $seq" for ((i = 0; i < length-1; i++)); do char="${seq:i:1}" charr="${seq:i+1:1}" if [[ "$char" != "$charr" ]]; then if [ "$char" == "G" ] && [ "$charr" == "R" ]; then seq=$(echo "$seq" | sed 's/GR/BB/') break fi if [ "$char" == "G" ] && [ "$charr" == "B" ]; then seq=$(echo "$seq" | sed 's/GB/RR/') break fi if [ "$char" == "R" ] && [ "$charr" == "B" ]; then seq=$(echo "$seq" | sed 's/RB/GG/') break fi if [ "$char" == "R" ] && [ "$charr" == "G" ]; then seq=$(echo "$seq" | sed 's/RG/BB/') break fi if [ "$char" == "B" ] && [ "$charr" == "R" ]; then seq=$(echo "$seq" | sed 's/BR/GG/') break fi if [ "$char" == "B" ] && [ "$charr" == "G" ]; then seq=$(echo "$seq" | sed 's/BG/RR/') break fi fi done iteration=$((iteration+1)) done ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully